JamesGill
JamesGill

Reputation: 323

Idiomatic way to handle errors with an early return in Rust

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();
    
    // ...

Upvotes: 4

Views: 3568

Answers (1)

Acorn
Acorn

Reputation: 26146

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,
};

Upvotes: 6

Related Questions