I'm writing a response handler for Axum, and I have a function that returns a Result<DraftTicket, Box<dyn Err>>
.
Here's what I currently have:
async fn create_ticket(extract::Json(draft): Json<TicketDraftRequest>, state: State<StateType>) -> Response {
// do our conversion check first
let draft = TicketDraft::try_from(draft);
if let Err(e) = draft {
return (StatusCode::BAD_REQUEST, e.to_string()).into_response();
}
let draft = draft.unwrap(); // we know this is OK
// rest of function
But that last unwrap
call seems off to me, and I'm wondering if there's a better way.
Putting it in a match statement seems non-ideal since I only want to return on error (and match would force me to nest the remaining part of the function).
I was wondering if there is some construct like this where I could transform the error into a Response and return that if error:
async fn create_ticket(extract::Json(draft): Json<TicketDraftRequest>, state: State<StateType>) -> Response {
// do our conversion check first
let draft = TicketDraft::try_from(draft).map_err(|e| {
(StatusCode::BAD_REQUEST, e.to_string()).into_response()
})?;
But the question mark operator doesn't work here (because the function returns a Response), so, is there a more rust-preferred solution to this type of flow, where you want to return a transformed error (on error) and otherwise continue? Or is what I did (just using unwrap) the correct solution?