惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
Netflix TechBlog - Medium
罗磊的独立博客
H
Help Net Security
I
Intezer
G
Google Developers Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
T
Troy Hunt's Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
N
News and Events Feed by Topic
J
Java Code Geeks
S
Security Affairs
T
The Blog of Author Tim Ferriss
Recent Commits to openclaw:main
Recent Commits to openclaw:main
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
D
Docker
The GitHub Blog
The GitHub Blog
F
Full Disclosure
N
News and Events Feed by Topic
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs
腾讯CDC
人人都是产品经理
人人都是产品经理
M
MIT News - Artificial intelligence
Blog — PlanetScale
Blog — PlanetScale
T
Threatpost
D
DataBreaches.Net
Recent Announcements
Recent Announcements
博客园 - 三生石上(FineUI控件)
MongoDB | Blog
MongoDB | Blog
博客园 - 【当耐特】
L
LINUX DO - 最新话题
Google Online Security Blog
Google Online Security Blog
S
Schneier on Security
S
Securelist
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Help Net Security
Help Net Security
P
Proofpoint News Feed
Project Zero
Project Zero
S
SegmentFault 最新的问题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MyScale Blog
MyScale Blog
Google DeepMind News
Google DeepMind News
宝玉的分享
宝玉的分享
Y
Y Combinator Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 叶小钗

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Error Handling in Axum
Syeed Talha · 2026-05-03 · via DEV Community

Axum is a web framework for Rust built on top of Tokio and Hyper. One of its
standout features is a simple and predictable error handling model — once
you understand the pattern, writing safe, expressive web servers becomes
surprisingly natural.

This guide walks you from the very basics to real-world patterns you'll use in
production.


The Core Idea: Errors Must Become Responses

In Axum, every error must eventually become an HTTP response. There is no
unhandled-exception mechanism. If something goes wrong, you decide what the
client sees — a 404, a 500, a JSON error body, or anything else.

The key trait is IntoResponse. Anything that implements it can be returned
from a handler, including error types.


1. The Simplest Error: Return a StatusCode

The easiest way to signal an error is to return a StatusCode directly.

use axum::{
    extract::Path,
    http::StatusCode,
    routing::get,
    Router,
};

async fn get_user(Path(id): Path<u32>) -> Result<String, StatusCode> {
    if id == 0 {
        return Err(StatusCode::NOT_FOUND);
    }
    Ok(format!("User #{}", id))
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/users/{id}", get(get_user)); // ✅ use {id}
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Enter fullscreen mode Exit fullscreen mode

Here the handler returns Result<String, StatusCode>. When Ok, Axum sends
the string as a 200 OK. When Err, it sends the status code you chose. Clean
and simple!


2. Returning Richer Errors with Tuples

A bare StatusCode doesn't tell the client why something went wrong. You can
pair a status code with a message using a tuple.

use axum::{http::StatusCode, routing::post, Json, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct CreateUser {
    username: String,
}

async fn create_user(
    Json(payload): Json<CreateUser>,
) -> Result<String, (StatusCode, String)> {
    if payload.username.is_empty() {
        return Err((
            StatusCode::BAD_REQUEST,
            "Username cannot be empty".to_string(),
        ));
    }

    Ok(format!("Created user: {}", payload.username))
}

Enter fullscreen mode Exit fullscreen mode

The tuple (StatusCode, String) is automatically turned into a response with
the given status and a text body. Axum knows how to convert it thanks to the
IntoResponse trait.


3. Building a Custom Error Type (The Right Way)

For real applications, you want a single error enum that covers all the things
that can go wrong. Then you implement IntoResponse for it so Axum can turn
your errors into HTTP responses automatically.

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

// Your application's error type
enum AppError {
    NotFound(String),
    Unauthorized,
    InternalError(String),
}

// Teach Axum how to turn your error into a response
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
            AppError::Unauthorized => (
                StatusCode::UNAUTHORIZED,
                "You are not authorized".to_string(),
            ),
            AppError::InternalError(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg),
        };

        (status, message).into_response()
    }
}

// Now use it in your handlers
async fn get_document(Path(id): Path<u32>) -> Result<String, AppError> {
    if id == 99 {
        return Err(AppError::Unauthorized);
    }
    if id > 100 {
        return Err(AppError::NotFound(format!("Document {} not found", id)));
    }
    Ok(format!("Document #{}", id))
}

Enter fullscreen mode Exit fullscreen mode

This is the pattern you'll use most often. One error type, one place to define
what each error looks like to clients.


4. Returning JSON Errors

APIs usually return JSON error bodies instead of plain text. Here's how to
return structured JSON from your error type.

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::Serialize;

#[derive(Serialize)]
struct ErrorBody {
    error: String,
    code: u16,
}

enum ApiError {
    NotFound(String),
    BadRequest(String),
    Internal,
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ApiError::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
            ApiError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg),
            ApiError::Internal => (
                StatusCode::INTERNAL_SERVER_ERROR,
                "Something went wrong".to_string(),
            ),
        };

        let body = Json(ErrorBody {
            error: message,
            code: status.as_u16(),
        });

        (status, body).into_response()
    }
}

Enter fullscreen mode Exit fullscreen mode

Now your clients get responses like:

{
  "error": "Document 999 not found",
  "code": 404
}

Enter fullscreen mode Exit fullscreen mode


5. Converting ? Errors with From

In real code, you'll use ? to propagate errors from libraries like database
drivers or HTTP clients. You can implement From<SomeError> for AppError to
make this seamless.

use std::num::ParseIntError;

enum AppError {
    BadRequest(String),
    Internal(String),
}

impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        // ... (same as above)
    }
}

// Convert ParseIntError into AppError automatically
impl From<ParseIntError> for AppError {
    fn from(err: ParseIntError) -> Self {
        AppError::BadRequest(format!("Invalid number: {}", err))
    }
}

async fn parse_id(Path(raw): Path<String>) -> Result<String, AppError> {
    // The `?` operator automatically calls From<ParseIntError> here
    let id: u32 = raw.parse()?;
    Ok(format!("Parsed id: {}", id))
}

Enter fullscreen mode Exit fullscreen mode

The ? after raw.parse() will, on failure, call your From impl and return
an Err(AppError::BadRequest(...)) — no manual conversion needed.


6. Using anyhow for Quick Prototyping

The anyhow crate is popular for applications where you don't need fine-grained
error types yet. You can bridge it into Axum with a small wrapper.

use anyhow::Context;
use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
};

// A wrapper so we can impl IntoResponse for anyhow::Error
struct AnyhowError(anyhow::Error);

impl IntoResponse for AnyhowError {
    fn into_response(self) -> Response {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Internal error: {}", self.0),
        )
            .into_response()
    }
}

// Allow using `?` on anyhow::Result in handlers
impl<E: Into<anyhow::Error>> From<E> for AnyhowError {
    fn from(err: E) -> Self {
        AnyhowError(err.into())
    }
}

async fn risky_handler() -> Result<String, AnyhowError> {
    let data = std::fs::read_to_string("config.txt")
        .context("Failed to read config file")?;
    Ok(data)
}

Enter fullscreen mode Exit fullscreen mode


7. Handler-Level Error Handling with HandleError

Sometimes you use a Tower Service or middleware that returns errors Axum
doesn't know how to handle. The HandleError layer lets you convert those.

use axum::{
    error_handling::HandleError,
    http::StatusCode,
    routing::get,
    Router,
};
use std::convert::Infallible;

async fn might_fail() -> Result<String, String> {
    Err("Something broke".to_string())
}

// Wrap the service to handle its errors
let service = tower::service_fn(|_req| async {
    Ok::<_, Infallible>("ok")
});

let handled = HandleError::new(service, |err: String| async move {
    (StatusCode::INTERNAL_SERVER_ERROR, err)
});

Enter fullscreen mode Exit fullscreen mode

This is more advanced and mainly relevant when integrating third-party Tower
services.


Quick Reference

Pattern Best For
Result<T, StatusCode> Simple, code-only errors
Result<T, (StatusCode, String)> Errors with a message
Custom enum + impl IntoResponse Production apps with typed errors
impl IntoResponse returning Json APIs that return JSON error bodies
impl From<LibError> for AppError Using ? with library errors
anyhow wrapper Quick prototypes or scripts

Summary

Axum's error handling boils down to one rule: your errors must implement
IntoResponse
. Once they do, you can use Result<T, YourError> in any
handler and Axum handles the rest.

The recommended path for most apps:

  1. Define an enum AppError with variants for each failure mode.
  2. Implement IntoResponse for it (returning JSON is usually best).
  3. Implement From<LibError> for AppError for each third-party error type you use with ?.
  4. Return Result<impl IntoResponse, AppError> from your handlers.

That's it. No magic, no hidden panics — just clean, explicit error paths.