IntoResponse for errors
Learn how an error type becomes an HTTP response in Axum by implementing IntoResponse with a status code and a message body
A handler has to answer every request with an HTTP response. When everything goes well, the handler returns a greeting, a page of data, or a JSON value, and Axum turns that value into a response. When something goes wrong, the handler still has to answer, and the answer is still an HTTP response: a status code like 404 and a short message that says what happened. IntoResponse is the piece that makes both cases work the same way. It is a trait, which in Rust means a shared set of behaviour that different types can implement, and its one job is to turn a value into a response.
Where This Fits
You already know that a handler returns a value and Axum sends it back as a response. A plain string becomes a 200 response with that string as the body. A tuple of a status code and a string becomes a response with that status and that body. This page adds the missing half of that picture: the value a handler returns can also be an error. The mechanism is the same one you already use for success values. There is no separate error channel, no exception system, and no special error return path. An error type that implements IntoResponse is returned from a handler exactly like a string or a JSON value, and Axum converts it into a response with the status code and body you chose.
Think of IntoResponse as a translator sitting between your handler and the network. Your handler speaks in Rust values. The client speaks in HTTP. The translator takes any value that knows how to describe itself as a response and does the conversion. Once you teach your error type to translate itself, every handler that returns it gets error responses for free.
The Smallest Working Version
Here is the smallest complete example. It defines one small error type with two cases, teaches it to turn itself into a response, and returns it from a handler.
# Cargo.toml
[package]
name = "axum-errors"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
Router,
};
#[derive(Debug)]
enum LookupError {
NotFound,
Broken,
}
impl IntoResponse for LookupError {
fn into_response(self) -> Response {
let (status, message) = match self {
LookupError::NotFound => (StatusCode::NOT_FOUND, "user not found"),
LookupError::Broken => (
StatusCode::INTERNAL_SERVER_ERROR,
"something broke on our side",
),
};
(status, message).into_response()
}
}
async fn get_user() -> LookupError {
LookupError::NotFound
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/1", get(get_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run, then ask for the route with curl:
curl -i http://127.0.0.1:3000/users/1
The terminal shows a real 404 response with the message as the body:
HTTP/1.1 404 Not Found
content-type: text/plain; charset=utf-8
content-length: 14
user not found
The handler never built a response by hand. It returned a plain Rust value, LookupError::NotFound, and Axum called the into_response method you wrote to produce the 404. That is the whole idea on this page: the handler decides what went wrong, and the IntoResponse implementation decides what the client sees.
Working Setup:
If curl shows 404 Not Found and the body user not found, the conversion works end to end. The handler returned an error value, the trait implementation turned it into a response, and Axum sent that response to the client.
Breaking Down the New Parts
Only three pieces of the example are new. The rest is a normal Axum server: a router, a route, a listener, and axum::serve. Here is what each new piece does.
The error type itself
#[derive(Debug)]
enum LookupError {
NotFound,
Broken,
}
An enum in Rust is a type that can be exactly one of a fixed list of cases, called variants. LookupError has two variants: the thing looked for was not found, and something broke while looking. Each variant is one kind of failure, and nothing else can be a LookupError. That matters because the conversion code can handle every case by name, and the compiler complains if a new variant is added later without handling it. The #[derive(Debug)] line asks the compiler to generate a way to print the value for debugging. It is a habit worth keeping on every error type, because you will want to log errors while you debug.
The trait implementation
impl IntoResponse for LookupError {
fn into_response(self) -> Response {
let (status, message) = match self {
LookupError::NotFound => (StatusCode::NOT_FOUND, "user not found"),
LookupError::Broken => (
StatusCode::INTERNAL_SERVER_ERROR,
"something broke on our side",
),
};
(status, message).into_response()
}
}
The trait IntoResponse has exactly one method: fn into_response(self) -> Response. It takes the value by value, which means it consumes the error. The error is used up by the conversion, and nothing of it remains afterwards. That fits, because an error value exists only to be turned into a response and sent away. Response is Axum's HTTP response type: a status code, headers, and a body, ready to send.
Inside the method, a match looks at which variant the error is and picks a status code and a message for it. StatusCode::NOT_FOUND is the number 404, and StatusCode::INTERNAL_SERVER_ERROR is the number 500. The names are constants from the http crate, which Axum re-exports, so you write the meaning instead of the number. The last line converts the (StatusCode, &str) tuple into a Response by calling into_response on the tuple itself. Tuples of a status code and a body already implement IntoResponse, so one conversion builds on another. That layering is a pattern you will use again and again: implement the trait for your type by delegating to an implementation that already exists.
The handler return type
async fn get_user() -> LookupError {
LookupError::NotFound
}
A handler can return any type that implements IntoResponse. That is the only rule. The handler above always returns the error, which makes it a clear demo, but in a real handler the error is only one of the possible returns. The next page covers the usual shape for that, a handler that returns either a success value or an error. For now, the point is that returning an error needs no extra ceremony. There is no wrapper, no special macro, and no error parameter. The return type is the error type, and Axum does the rest.
The Error Is a Value, Not a Crash:
Returning an error from a handler is normal program flow, not a crash. The server keeps running and keeps answering other requests. A crash would be a panic, which stops the task that handles the request. An error response is a deliberate answer, and the client can read it and decide what to do next.
What IntoResponse Actually Promises
The trait is a contract with one sentence: this type knows how to become an HTTP response. Axum already implements it for the types a beginner reaches for first. A &str becomes a 200 response with that text as the body. A String does the same. A StatusCode on its own becomes a response with that status and an empty body. A tuple of a status code and a body becomes a response with both. Json<T> becomes a 200 response with a JSON body. Tuples of up to several parts, mixing status codes, headers, and bodies, also work. Your error type joins that list the moment you write the impl block.
The contract also explains what a handler return type must satisfy. When you write .route("/users/1", get(get_user)), Axum checks at compile time that the handler's return type implements IntoResponse. If it does not, the code does not compile. That check is the safety net for this whole style of error handling. A missing conversion is caught before the server ever starts, instead of failing on the first bad request in front of a real user.
One more part of the contract is worth stating plainly. The conversion runs once, at the moment the handler returns. The handler itself never sees the Response. It works with ordinary Rust values, and the translation to HTTP happens after it finishes. That split keeps handler code readable: the handler says what happened, and the trait implementation says what the client should see.
Why the Conversion Lives in One Place
It is tempting to build the response inside the handler, with a match that returns a different tuple for each failure. That works for one handler. It falls apart when five handlers can all fail the same way, because each one repeats the same status codes and messages, and they drift apart over time. One handler says "user not found" with a 404, another says "no such user" with a 400, and a client cannot tell whether the two mean the same thing.
Putting the conversion in the IntoResponse implementation fixes that by giving each kind of failure exactly one translation. Every handler that returns LookupError::NotFound produces the same 404 with the same message, because there is only one place that decides what NotFound means on the wire. When the message needs to change, it changes in one place. When a new failure kind appears, it gets one new variant and one new arm in the match, and every handler benefits at once.
This is also why the error type carries no HTTP knowledge in its variants. NotFound does not store a status code. It stores the fact that something was not found. The status code is a presentation decision, made in into_response, where it belongs. The handler code stays about the problem, and the trait implementation stays about the response.
A Richer Complete Example
A two-variant error with fixed messages is enough to learn the shape, but a real lookup needs to say which thing was missing. Here is a small book catalogue where the error carries the id that was not found, and one return type covers both the found case and the missing case.
use axum::{
Json, Router,
extract::Path,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
};
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
struct Book {
id: u32,
title: String,
}
fn find_book(id: u32) -> Option<Book> {
let books = [
Book {
id: 1,
title: "The Rust Book".to_string(),
},
Book {
id: 2,
title: "Zero to Production".to_string(),
},
];
books.into_iter().find(|book| book.id == id)
}
enum BookOutcome {
Found(Book),
Missing(u32),
}
impl IntoResponse for BookOutcome {
fn into_response(self) -> Response {
match self {
BookOutcome::Found(book) => (StatusCode::OK, Json(book)).into_response(),
BookOutcome::Missing(id) => (
StatusCode::NOT_FOUND,
format!("no book with id {id}"),
)
.into_response(),
}
}
}
async fn get_book(Path(id): Path<u32>) -> BookOutcome {
match find_book(id) {
Some(book) => BookOutcome::Found(book),
None => BookOutcome::Missing(id),
}
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/books/{id}", get(get_book));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The Cargo.toml needs serde with the derive feature for the Serialize derive on Book:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
find_book returns an Option<Book>, which is Rust's way of saying a value may or may not be there. Some(book) means the book exists, and None means it does not. The handler turns that Option into a BookOutcome: found books become Found, and a missing id becomes Missing(id), carrying the id along so the message can name it.
The into_response implementation shows two different conversions in one match. The success arm returns the book as JSON with a 200 status, using the Json wrapper that serialises the struct. The failure arm builds a message with format!, which fills the id into the text. A request for /books/1 returns {"id":1,"title":"The Rust Book"} with status 200. A request for /books/9 returns status 404 with the body no book with id 9. Both answers come from the same return type and the same conversion method.
This shape, one enum with a variant per outcome and one match that translates each variant, is the pattern the rest of error handling in Axum is built on. The chapter later builds one shared error type from this idea, so that every handler in an application speaks the same error language.
A Variant That Carries Data Needs a Message That Uses It:
When a variant carries data, like Missing(u32), the message should use that data. A generic message such as "book not found" throws away the one detail the client needs to tell two missing books apart. If a variant carries an id, put the id in the body. If it carries a reason, put the reason in the body.
Returning a Status Code on Its Own
Sometimes there is nothing useful to say beyond the status itself. A route that only exists to say "this id does not exist" can return a bare StatusCode:
use axum::{http::StatusCode, routing::get, Router};
async fn only_status() -> StatusCode {
StatusCode::NOT_FOUND
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/only-status", get(only_status));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
A request to this route returns status 404 with an empty body. Axum's implementation for StatusCode sets the status and sends nothing else. That is correct behaviour for a status that carries its whole meaning in the number, such as 204 No Content after a delete, or a bare 404 from a probe that only checks whether something exists. It is the wrong choice when a human or a client program needs to know why the request failed, because an empty body gives them nothing to work with. Use a bare status code when the status alone is the full answer, and use a tuple or a custom error type when the answer needs words.
Building a Response From Parts Inside the Implementation
The implementations so far delegated to a tuple. That delegation is the usual approach, but it helps to see that into_response is ordinary code. It can build the response piece by piece, and it can call into_response on any value that already implements the trait. A second style for the same error shows the moving parts:
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
#[derive(Debug)]
enum LookupError {
NotFound,
Broken,
}
impl IntoResponse for LookupError {
fn into_response(self) -> Response {
match self {
LookupError::NotFound => {
let body = "user not found".to_string();
(StatusCode::NOT_FOUND, body).into_response()
}
LookupError::Broken => {
let body = "something broke on our side".to_string();
(StatusCode::INTERNAL_SERVER_ERROR, body).into_response()
}
}
}
}
Each arm builds its own body string and its own tuple, then converts that tuple. The result is identical to the compact version: the same status, the same body. The compact version is easier to read when every arm is a short pair, and the expanded version is easier to read when an arm needs extra work first, such as formatting a message from the data a variant carries, or choosing between two messages based on a field. Both are the same trait doing the same job. Pick the shape that keeps the match readable as the number of variants grows.
What Happens From Handler Return to Client
The request flow for an error looks like this in plain text:
Client sends GET /users/1
|
v
Router matches the path and calls the handler
|
v
Handler returns LookupError::NotFound
|
v
Axum calls LookupError::into_response
|
v
The match picks 404 and "user not found"
|
v
The tuple becomes a Response with status 404
|
v
Axum writes the response to the socket
|
v
Client receives 404 with the message as the body
Nothing in this flow can fail in a way that leaves the client hanging. The handler always returns a value, the value always converts to a response, and the response is always sent. That guarantee is the reason Axum requires handler return types to implement IntoResponse. It is enforced by the compiler, not by discipline, so a forgotten error case is a compile error instead of a missing response at runtime.
Testing It
Tests for error responses use the same oneshot style as tests for success responses. They send a request straight to the router without starting a server, then check the status and the body. The tower crate provides the oneshot method, and it belongs in the dev-dependencies of Cargo.toml:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
use axum::{
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use axum_errors::app;
use tower::ServiceExt;
#[tokio::test]
async fn missing_user_returns_404_with_message() {
let response = app()
.oneshot(
Request::builder()
.uri("/users/1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert_eq!(String::from_utf8(bytes.to_vec()).unwrap(), "user not found");
}
#[tokio::test]
async fn missing_book_names_the_id() {
let response = app()
.oneshot(
Request::builder()
.uri("/books/9")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
assert_eq!(
String::from_utf8(bytes.to_vec()).unwrap(),
"no book with id 9"
);
}
For these tests to work, the application needs to live in src/lib.rs so the test file can import it, with src/main.rs reduced to starting the server. The library file holds the router and the handlers:
use axum::{
Json, Router,
extract::Path,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
};
use serde::Serialize;
#[derive(Debug)]
pub enum LookupError {
NotFound,
Broken,
}
impl IntoResponse for LookupError {
fn into_response(self) -> Response {
let (status, message) = match self {
LookupError::NotFound => (StatusCode::NOT_FOUND, "user not found"),
LookupError::Broken => (
StatusCode::INTERNAL_SERVER_ERROR,
"something broke on our side",
),
};
(status, message).into_response()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Book {
pub id: u32,
pub title: String,
}
pub fn find_book(id: u32) -> Option<Book> {
let books = [
Book {
id: 1,
title: "The Rust Book".to_string(),
},
Book {
id: 2,
title: "Zero to Production".to_string(),
},
];
books.into_iter().find(|book| book.id == id)
}
pub enum BookOutcome {
Found(Book),
Missing(u32),
}
impl IntoResponse for BookOutcome {
fn into_response(self) -> Response {
match self {
BookOutcome::Found(book) => (StatusCode::OK, Json(book)).into_response(),
BookOutcome::Missing(id) => (
StatusCode::NOT_FOUND,
format!("no book with id {id}"),
)
.into_response(),
}
}
}
pub async fn get_user() -> LookupError {
LookupError::NotFound
}
pub async fn get_book(Path(id): Path<u32>) -> BookOutcome {
match find_book(id) {
Some(book) => BookOutcome::Found(book),
None => BookOutcome::Missing(id),
}
}
pub fn app() -> Router {
Router::new()
.route("/users/1", get(get_user))
.route("/books/{id}", get(get_book))
}
use axum_errors::app;
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app()).await.unwrap();
}
Run the tests with cargo test. Both tests pass, and each one checks the two things that matter about an error response: the status code is right, and the body says what went wrong. Checking only the status would miss a message that names the wrong id, and checking only the body would miss a 200 status on a failure.
Common Beginner Mistakes
Returning an error type without the trait implementation
// Wrong - does not compile
use axum::{routing::get, Router};
#[derive(Debug)]
enum LookupError {
NotFound,
}
async fn get_user() -> LookupError {
LookupError::NotFound
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/1", get(get_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The compiler rejects this with an error saying the handler does not satisfy the trait bounds, because LookupError does not implement IntoResponse. Axum has no way to turn the value into a response, so it refuses to build the route. The fix is the impl IntoResponse for LookupError block from the smallest example. Every custom error type needs one before any handler can return it.
A Missing Implementation Is a Compile Error, Not a Runtime Surprise:
When the compiler reports that a handler return type does not implement IntoResponse, the answer is always to add the implementation or to change the return type to one that already has it. Do not work around the error by converting the error to a string inside the handler, because that throws away the status code and turns every failure into a 200 response.
Reaching for a standard library error type directly
// Wrong - does not compile as a handler return
use axum::{routing::get, Router};
use std::io;
async fn read_something() -> io::Result<String> {
Ok("data".to_string())
}
std::io::Error does not implement IntoResponse, so a handler cannot return it directly, and neither can io::Result<String>. The standard library error types know nothing about HTTP, so they have no opinion about which status code a failure deserves. The fix is to define your own error type, implement IntoResponse for it, and convert library errors into it. That conversion is a small match or a From implementation, and it is where you decide that a missing file means 404 while a permission failure means 500. The decision belongs to you, because only you know what the failure means for your application.
Turning an error into a panic with unwrap
// Wrong - turns a normal failure into a crash of the request task
async fn get_user() -> String {
let user = load_user(1).unwrap();
user.name
}
unwrap on a Result panics when the value is an Err, and a panic inside a handler aborts that request instead of answering it. The client gets a dropped connection instead of a 404, and the server logs a panic for something that was an ordinary missing user. The fix is to return the error instead of unwrapping it: give the handler a return type that can carry the failure, and let IntoResponse turn it into a proper response. Unwrap is for errors that cannot happen, and a missing user is an error that certainly can.
Every unwrap in a Handler Is a Response You Refused to Send:
When you write unwrap inside a handler, ask what the client should receive if the value is missing. If there is an answer, return an error type that produces it. If there is genuinely no answer because the failure cannot happen, the code around it should make that obvious, and the next page shows the type that says exactly that.
Final Complete Example
Here is everything from this page put together in one project: the small error type, the book catalogue with its own outcome type, the routes, and the server startup.
use axum::{
Json, Router,
extract::Path,
http::StatusCode,
response::{IntoResponse, Response},
routing::get,
};
use serde::Serialize;
#[derive(Debug)]
pub enum LookupError {
NotFound,
Broken,
}
impl IntoResponse for LookupError {
fn into_response(self) -> Response {
let (status, message) = match self {
LookupError::NotFound => (StatusCode::NOT_FOUND, "user not found"),
LookupError::Broken => (
StatusCode::INTERNAL_SERVER_ERROR,
"something broke on our side",
),
};
(status, message).into_response()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct Book {
pub id: u32,
pub title: String,
}
pub fn find_book(id: u32) -> Option<Book> {
let books = [
Book {
id: 1,
title: "The Rust Book".to_string(),
},
Book {
id: 2,
title: "Zero to Production".to_string(),
},
];
books.into_iter().find(|book| book.id == id)
}
pub enum BookOutcome {
Found(Book),
Missing(u32),
}
impl IntoResponse for BookOutcome {
fn into_response(self) -> Response {
match self {
BookOutcome::Found(book) => (StatusCode::OK, Json(book)).into_response(),
BookOutcome::Missing(id) => (
StatusCode::NOT_FOUND,
format!("no book with id {id}"),
)
.into_response(),
}
}
}
pub async fn get_user() -> LookupError {
LookupError::NotFound
}
pub async fn get_book(Path(id): Path<u32>) -> BookOutcome {
match find_book(id) {
Some(book) => BookOutcome::Found(book),
None => BookOutcome::Missing(id),
}
}
pub fn app() -> Router {
Router::new()
.route("/users/1", get(get_user))
.route("/books/{id}", get(get_book))
}
use axum_errors::app;
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app()).await.unwrap();
}
# Cargo.toml
[package]
name = "axum-errors"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the server with cargo run and the tests with cargo test. A request for /books/1 returns the book as JSON with status 200, a request for /books/9 returns 404 with the body no book with id 9, and a request for /users/1 returns 404 with the body user not found. Two error types, two conversions, and one rule behind both of them.
Summary
The single insight to carry away is that errors and successes travel through the same door. A handler returns a value, and IntoResponse decides what the client receives. That sameness is what makes error handling in Axum feel small: there is no second system to learn, only one trait to implement for each error type you define. The decision framework follows from it. When a failure has one fixed meaning, return the error type directly and let its implementation pick the status and the message. When a failure needs words that depend on the request, carry the details in the variant and format them in the implementation. When the status alone is the whole answer, return the status code itself. And when one handler can both succeed and fail, which is the common case, the return type needs room for both outcomes at once, so the next idea to reach for is a handler that returns a Result, where the success value and the error value each get converted by the same trait.