Dev.to WebDev 🛠 Dev 👁 0

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

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()
    }
}

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:

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.