DEV Community

AutoLab Systems
AutoLab Systems

Posted on

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

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 }))).into_response()
    }
}
Enter fullscreen mode Exit fullscreen mode

Want Production-Ready .cursorrules & Boilerplates?

I'm a student developer in Japan funding my upcoming new life next spring by packaging strict, battle-tested AI coding setups:

Top comments (0)