Idiomatic way to handle errors with an early return in Rust
Full error message
I currently have the below code to handle the case where I want to handle an error without propagation or continue the function. The use case for this is a web server controller, where I would prefer to manual handle possible errors - which is why the return type is HttpResponse.
I want to know if there is a way to do this without this unwrap call as in my understanding the compiler should know there is a way to unwrap to a value at this point with no risk of panic.
// ...
let result: Result<u8, Error> = func_that_could_error();
if result.is_err() {
return HttpResponse::InternalServerError();
}
let value: u8 = result.unwrap();
// ...Solutionsource: stackoverflow \u2197
If you can, use ?: let value = func_that_could_error()?; Optionally mapping it to your error as @Jmb suggests: let value = func_that_could_error() .map_err(|_| HttpResponse::InternalServerError())?; Otherwise, use let else: let Ok(value) = func_that_could_error() else { return HttpResponse::InternalServerError(); }; Or, for Rust < 1.65, match: let value = match func_that_could_error() { Err(_) => return HttpResponse::InternalServerError(), Ok(v) => v, };
API access
Get this solution programmatically \u2014 free, no authentication.
curl https://depscope.dev/api/error/796d4694dcc9393caf5eec7e39284ff27d9f6ea08b6efc6e940d6c094e2bb326hash \u00b7 796d4694dcc9393caf5eec7e39284ff27d9f6ea08b6efc6e940d6c094e2bb326