Menu

Rust Axum Backend Essentials: Zero-Unwrap Error Mapping for Crash-Proof APIs
📰

Rust Axum Backend Essentials: Zero-Unwrap Error Mapping for Crash-Proof APIs

DEV Community: rust·AutoLab Systems·13 days ago
#jR9KBzG6
#devtorust#devto#dev#error#intoresponse
Reading 0:00
15s threshold

Rust gives you memory safety, but calling .unwrap() inside an Axum web handler will still panic and kill the handler task on unexpected input.

Clean Error Handling With IntoResponse

Define a domain error enum using thiserror and implement IntoResponse once so handlers can cleanly use the ? operator:

use axum :: { http :: StatusCode , response :: { IntoResponse , Response } , Json } ; use serde_json :: json ;

enum ApiError { NotFound , Internal , }

impl IntoResponse for ApiError { fn into_response ( self ) -> Response { let ( status , msg ) = match self { ApiError :: NotFound => ( StatusCode :: NOT_FOUND , "Resource not found" ) , ApiError :: Internal => ( StatusCode :: INTERNAL_SERVER_ERROR , "Internal error" ) , } ; ( status , Json ( json! ( { "error" : msg } ) ) ) .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.