From impl for AppError
Learn how implementing From for AppError lets the question mark operator turn file and JSON errors into HTTP error responses automatically
A handler that reads a file can fail in two different ways. The file might be missing, which gives an input-output error. The file might hold broken JSON, which gives a parsing error. Both failures need to end up as the same thing, an AppError that Axum can turn into an HTTP response. Writing a From implementation for each error type is the piece that connects them.
Where This Fits
The custom rejection override showed how a failed extractor becomes a value the handler can deal with instead of a response Axum builds on its own. This page covers the other direction. Inside the handler body, ordinary Rust code fails with ordinary Rust error types, and those errors still need to become an AppError. The From implementations in this page are the bridge between the two worlds.
Think of From as a translator standing between two people who speak different languages. The file code speaks the language of input-output errors. The parsing code speaks the language of JSON errors. The handler speaks the language of AppError. One small translator for each language keeps the handler itself free of translation work.
The Smallest Working Version
Here is the smallest project that shows the idea end to end. It has a configuration file, a handler that reads it, and two From implementations that convert the two possible failures into AppError.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
impl From<std::io::Error> for AppError {
fn from(error: std::io::Error) -> Self {
eprintln!("io error: {error}");
AppError::InternalError
}
}
impl From<serde_json::Error> for AppError {
fn from(error: serde_json::Error) -> Self {
eprintln!("json error: {error}");
AppError::InternalError
}
}
The file above holds the whole error type. The enum lists the three kinds of failure the application knows how to answer. The IntoResponse implementation turns each variant into a status code and a JSON body with one error key, using the message from the thiserror attribute. The two From implementations at the bottom are new here. Each one takes a foreign error, writes its detail to the server log with eprintln!, and returns AppError::InternalError. The client never sees the detail. The log keeps it for the developer.
pub mod errors;
use axum::{Json, Router, routing::get};
use errors::AppError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
pub name: String,
pub port: u16,
}
pub fn app() -> Router {
Router::new().route("/config", get(read_config))
}
async fn read_config() -> Result<Json<Config>, AppError> {
let text = tokio::fs::read_to_string("config.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(Json(config))
}
The handler does three things and nothing else. It reads the file, parses the text into a Config, and returns the result as JSON. Both fallible lines end with ?, the question mark operator. There is no match, no map_err, and no mention of AppError inside the handler body. The ? operator does the conversion work, and the From implementations tell it how.
use axum_project::app;
#[tokio::main]
async fn main() {
let app = app();
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 entry point stays thin. It builds the router, binds a listener on port 3000, and serves the application. Nothing about errors lives here.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
The dependencies are the ones this page uses. tokio needs the full feature set because the handler uses tokio::fs, the asynchronous file reading module. thiserror provides the Error derive macro used on the enum. serde_json provides both the from_str parsing function and the json! macro used in the response body.
{"name": "demo", "port": 3000}
The configuration file sits in the project root, next to Cargo.toml. It holds a name and a port number. Running the server from the project root with cargo run and requesting the route shows the happy path working.
curl http://127.0.0.1:3000/config
{"name":"demo","port":3000}
Deleting the file and requesting again shows the first conversion in action. The file read fails with an input-output error, ? converts it through the From implementation into AppError::InternalError, and the response carries the generic message.
curl http://127.0.0.1:3000/config
{"error":"something went wrong"}
The terminal running the server also prints the log line from the From implementation, so the real cause is not lost.
io error: No such file or directory (os error 2)
Restoring the file with broken content, such as a port written as a word instead of a number, shows the second conversion. The read succeeds, the parse fails, and the client sees the same generic body while the log keeps the detail.
{"name": "demo", "port": "not-a-number"}
curl http://127.0.0.1:3000/config
{"error":"something went wrong"}
json error: invalid type: string "not-a-number", expected u16 at line 1 column 36
Working Setup:
If the good file returns the configuration as JSON and the missing or broken file returns a 500 response with the body {"error":"something went wrong"}, the two conversions are wired up correctly. The log lines in the server terminal confirm the detail went to the log and not to the client.
How the Question Mark Operator Uses From
The ? operator looks small, but it does two jobs at once. On success it unwraps the value out of the Result and lets the function carry on. On failure it stops the function early and returns the error to the caller. Between those two jobs sits a conversion step that most beginners never see, and that step is the whole point of this page.
When the function returns Result<Json<Config>, AppError> and the ? meets an Err holding a std::io::Error, the operator does not hand that error back as it is. The types would not match. It first calls From::from on the error, which runs the implementation written in errors.rs, and returns the resulting AppError instead. The same happens for a serde_json::Error on the parsing line. One operator, two different source types, one target type, and no conversion code at the call site.
The equivalent code without ? makes the hidden step visible. This is the same handler written out by hand, and it shows exactly what ? replaces.
async fn read_config_verbose() -> Result<Json<Config>, AppError> {
let text = match tokio::fs::read_to_string("config.json").await {
Ok(text) => text,
Err(error) => return Err(AppError::from(error)),
};
let config: Config = match serde_json::from_str(&text) {
Ok(config) => config,
Err(error) => return Err(AppError::from(error)),
};
Ok(Json(config))
}
Each match arm repeats the same shape. On the error arm it calls AppError::from(error) explicitly and returns early. The ? version is shorter because the compiler writes this shape for the reader. Nothing else changes. The behaviour, the log line, and the response are identical in both versions.
From and Into Are Two Sides of One Conversion:
From and Into describe the same conversion from opposite ends. Writing impl From<std::io::Error> for AppError also gives the reverse direction for free, so io_error.into() produces an AppError too. The standard library provides that reverse direction automatically. Always write the From side, because it is the side the ? operator calls, and the Into side follows without extra code.
The From Trait Itself
From is a trait from the standard library, which is the collection of basic tools that ships with every Rust program. A trait is a named set of methods that a type promises to provide. From promises exactly one method, from, which takes a value of one type and returns a value of another type. Its whole definition fits in a few lines.
pub trait From<T> {
fn from(T) -> Self;
}
The definition says that for some input type T, the implementing type knows how to build itself from a T value. There is no Result in the return type. A From conversion cannot fail, and it cannot report a failure. That rule shapes every decision on this page. If a conversion needs to make a choice that could go wrong, it does not belong in From. It belongs in ordinary handler code, where the failure can be handled openly.
The from method takes ownership of the incoming error, which means it consumes the value. Nothing else can use that error afterwards. That is fine here, because the only things done with it are logging its message and discarding it in favour of the generic variant. Rust allows the implementation because AppError belongs to this project, even though the From trait and the source error come from elsewhere.
Why Both Conversions Map to InternalError
Both implementations return the same variant, and that sameness is a decision, not a coincidence. A missing configuration file is a problem on the server side. The client sent a correct request and cannot fix a missing file by changing anything it sends. A broken configuration file is the same kind of problem. The file lives on the server, the client did not write it, and no change to the request repairs it. Both failures are therefore internal errors, and both answer with status 500 and a generic message.
The message the client sees never contains the file path, the operating system error, or the parse detail. Those details help the developer and nobody else. A client that learns the server reads a file called config.json from its working directory has learned something about the server layout that it does not need. The eprintln! line keeps the detail where it belongs, in the server log, and the response keeps the generic text.
A common wrong turn is mapping the JSON parse failure to the validation variant instead. It looks tempting, because the word validation sounds like it covers bad data. It is wrong here for one plain reason. The validation variant means the client sent bad input. The configuration file is not client input. Sending a 422 response for a broken server file tells the client it did something wrong when it did nothing wrong, and a client that retries with different input will fail again in exactly the same way.
A Shared Helper That Reuses the Conversions
A handler is not the only function that can use ?. Any function that returns Result<T, AppError> gets the same conversions for free. That matters as soon as two handlers need the same file, because the loading logic can move into one helper and both handlers call it.
async fn load_config() -> Result<Config, AppError> {
let text = tokio::fs::read_to_string("config.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(config)
}
async fn config_via_helper() -> Result<Json<Config>, AppError> {
let config = load_config().await?;
Ok(Json(config))
}
The helper returns a plain Config instead of a JSON response. Its two ? operators convert exactly as they did in the handler, because the return type is still a Result with AppError on the error side. The handler then calls the helper with one more ?. That last ? needs no conversion at all, because the helper already returns AppError. The compiler only converts when the types differ, and here they already match.
This shape scales well. A second handler that needs the same configuration calls the same helper instead of copying the file reading code. When a third error type appears later, one new From implementation in errors.rs teaches every helper and every handler at once, instead of touching each call site.
Adding a Third Conversion
New error types appear as the application grows, and the decision for each one follows the same two questions. Whose fault is the failure, and what should the client see? A parsing failure for a number the user typed is a client fault, so it maps to the validation variant with a short message. The standard library type for that failure is std::num::ParseIntError, which is the error returned when text cannot be parsed into a number.
impl From<std::num::ParseIntError> for AppError {
fn from(_error: std::num::ParseIntError) -> Self {
AppError::ValidationError("port must be a number".to_string())
}
}
The underscore before error marks the value as intentionally unused. The parse detail is not logged here, because the message itself says everything the developer needs, and the client gets a message it can act on. A handler that parses a port number from text can now use ? on the parse call with no extra code.
async fn read_port(text: &str) -> Result<u16, AppError> {
let port: u16 = text.trim().parse()?;
Ok(port)
}
Calling this helper with "abc" returns the validation variant, which answers with status 422 and the body {"error":"port must be a number"}. Calling it with "3000" returns the number. The same operator, the same rule, a different target variant, chosen because the fault sits with the input rather than the server.
A Conversion Must Not Fail:
From promises the conversion always succeeds, so the body of from must never panic, never unwrap, and never call code that can fail. If the conversion needs a decision that could go wrong, such as choosing between two variants based on data that might be missing, write a small function that returns a Result and call it from the handler instead. A panic inside from would crash the task handling the request, which is a far worse outcome than the original error.
The Manual Alternative and When It Still Fits
Before From existed in a project, handlers converted errors by hand with map_err, a method on Result that runs a small function on the error value and leaves the success value alone. The shape looks like this.
async fn read_config_manual() -> Result<Json<Config>, AppError> {
let text = tokio::fs::read_to_string("config.json")
.await
.map_err(|_| AppError::InternalError)?;
let config: Config = serde_json::from_str(&text)
.map_err(|_| AppError::InternalError)?;
Ok(Json(config))
}
This version compiles and behaves the same from the outside. It is worse in two ways that grow with the size of the project. Every fallible call repeats the same closure, so a handler with five fallible calls carries five copies of the conversion. And the conversion lives at the call site, so changing the mapping means editing every handler instead of one implementation. The From version keeps the mapping in exactly one place.
map_err still has a genuine use. A conversion that needs information only the handler has, such as which file was being read or which user was involved, cannot live in From, because from only receives the error itself. In that case a map_err closure at the call site can build a richer message from the surrounding context. The rule is simple. A conversion that depends only on the error goes in From. A conversion that depends on the surrounding context stays in the handler with map_err.
Which Conversions to Write and Which Not to Write
Not every error type deserves a From implementation. Each one added is a promise that every occurrence of that error, anywhere in the application, means the same thing and deserves the same response. That promise is easy to keep for a small set and easy to break for a large one. The table below collects the decisions this page makes, with the reasoning short enough to apply to the next error type that shows up.
| Source error | Target variant | Reason |
|---|---|---|
std::io::Error | InternalError | File and network failures on the server side are not the client's fault |
serde_json::Error | InternalError | Parsing a server-side file that the client did not send |
std::num::ParseIntError | ValidationError | Text that was supposed to be a number did not parse, and the input can be fixed by the sender |
The conversions to avoid are just as important. A From<String> implementation would let any string become an error, which hides where the error came from and invites handlers to return ad hoc messages instead of using the named variants. A conversion from a catch-all error type that wraps any failure would swallow the distinction between client faults and server faults. A conversion for an error type the handler never produces adds a promise nobody uses, and a reader of errors.rs cannot tell which conversions are live and which are dead.
One more shape deserves a warning. Rust already provides a reflexive implementation, which means From<AppError> for AppError exists without any code, because every type converts into itself. Writing it by hand is unnecessary, and the compiler rejects a duplicate. The same applies to writing two From implementations for the same source type. The compiler treats that as a conflicting implementation and refuses to build, because a single ? would have two different answers.
A Plain Text Diagram of the Flow
The path an error takes from the failing call to the client has four stops, and each stop belongs to a different piece of code.
tokio::fs::read_to_string fails
|
v
? operator catches the Err value
|
v
From<std::io::Error> for AppError runs
|
v
handler returns Err(AppError::InternalError)
|
v
IntoResponse turns it into 500 + `{"error": "something went wrong"}`
|
v
client receives the JSON body
The handler body only appears once in that diagram, at the top. Everything below it is machinery the handler never sees. That is the point of the design.
Testing the Conversions
A conversion is only trustworthy when a test shows the response it produces. The tests below send requests through the router without starting a real server, using the oneshot method from the tower crate. Each test checks both the status code and the exact body, because the conversion is only correct when both match.
use axum::{
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn body_text(response: axum::response::Response) -> String {
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn config_ok_returns_parsed_config() {
let response = app()
.oneshot(
Request::builder()
.uri("/config")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body_text(response).await, r#"{"name":"demo","port":3000}"#);
}
#[tokio::test]
async fn missing_file_becomes_500_with_generic_body() {
let response = app()
.oneshot(
Request::builder()
.uri("/config-missing")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(
body_text(response).await,
r#"{"error":"something went wrong"}"#
);
}
#[tokio::test]
async fn broken_json_becomes_500_without_leaking_detail() {
let response = app()
.oneshot(
Request::builder()
.uri("/config-broken")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = body_text(response).await;
assert_eq!(body, r#"{"error":"something went wrong"}"#);
assert!(!body.contains("not-a-number"));
assert!(!body.contains("invalid type"));
}
The third test is the one that guards the design decision. It does not only check the status and the body. It also asserts that the body does not contain the words from the parse error. If somebody later changes the From implementation to forward the detail into the response, this test fails and the leak is caught before it reaches a client. The routes /config-missing and /config-broken in the test are small handlers that read missing.json and broken.json, using the same two ? lines as the main handler. They exist only to make the failure paths testable.
async fn read_broken_config() -> Result<Json<Config>, AppError> {
let text = tokio::fs::read_to_string("broken.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(Json(config))
}
async fn read_missing_config() -> Result<Json<Config>, AppError> {
let text = tokio::fs::read_to_string("missing.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(Json(config))
}
Running cargo test prints the log lines from the From implementations alongside the test results, which is a useful check that the logging side of the conversion runs. The test run itself stays green while the detail flows to the terminal where the developer can read it.
Common Beginner Mistakes
Using Question Mark Without a From Implementation
This is the mistake every beginner meets first, and the compiler message names the fix directly.
// Wrong - won't compile
async fn read_config() -> Result<Json<Config>, AppError> {
let text = tokio::fs::read_to_string("config.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(Json(config))
}
Without the From implementations in errors.rs, the code above fails with this error.
error[E0277]: `?` couldn't convert the error to `AppError`
the trait `From<std::io::Error>` is not implemented for `AppError`
note: `AppError` needs to implement `From<std::io::Error>`
= note: the question mark operation (`?`) implicitly performs a conversion
on the error value using the `From` trait
The fix is the implementation itself, not a change to the handler. Add impl From<std::io::Error> for AppError and the same shape for serde_json::Error, and the handler compiles untouched. When this error appears, it is always a missing conversion, never a problem with the handler logic.
The Compiler Points at the Question Mark:
The E0277 error points at the ? operator, not at the function that failed. Beginners often rewrite the handler or change the return type when they see it. Read the note underneath instead. It names the exact trait and the exact types, which is the implementation that needs writing.
Writing Into Instead of From
// Wrong - the ? operator does not use this direction
impl Into<AppError> for std::io::Error {
fn into(self) -> AppError {
AppError::InternalError
}
}
This code also fails, because Rust forbids implementing a foreign trait for a foreign type pair in this direction, and because the standard library already provides Into from From. The rule to remember is one line. Implement From, never Into. The ? operator calls From::from, and the blanket implementation in the standard library supplies Into automatically.
Mapping a Server Failure to the Validation Variant
// Wrong - a broken server file is not bad client input
impl From<serde_json::Error> for AppError {
fn from(error: serde_json::Error) -> Self {
AppError::ValidationError(error.to_string())
}
}
This version compiles, which makes it more dangerous than the ones that do not. It answers a broken configuration file with status 422, which tells the client its input was wrong, and it puts the full parse detail into the response body, which leaks server internals. Both problems come from one wrong choice of variant. The fix is to return InternalError and log the detail instead of forwarding it.
Forgetting the Log Line
// Wrong - the detail is thrown away with no record anywhere
impl From<std::io::Error> for AppError {
fn from(_error: std::io::Error) -> Self {
AppError::InternalError
}
}
Dropping the error without logging it leaves the developer blind. The client sees a generic 500, the server log shows nothing, and nobody can tell whether the file was missing, unreadable, or something else entirely. The eprintln! line in the working version costs one line and saves that whole investigation. In a real application the same spot is where a logging call belongs.
Using Question Mark in a Function That Returns Something Else
// Wrong - ? converts into the function's own error type, not AppError
async fn read_config_text() -> Result<String, std::io::Error> {
let text = tokio::fs::read_to_string("config.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(text)
}
The second ? in this function fails to compile, because the function returns Result<String, std::io::Error> and there is no conversion from serde_json::Error into std::io::Error. The ? operator always converts into the error type of the enclosing function. A helper that mixes error types must return Result<T, AppError> for the conversions on this page to apply.
Final Complete Example
Here is everything from this page put together in one project. The error file carries the enum, the response mapping, and all three conversions. The library file carries the configuration type, the shared helper, and the handlers. The test file proves the three outcomes.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum AppError {
#[error("resource not found")]
NotFound,
#[error("{0}")]
ValidationError(String),
#[error("something went wrong")]
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = match &self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
};
let body = Json(json!({ "error": self.to_string() }));
(status, body).into_response()
}
}
impl From<std::io::Error> for AppError {
fn from(error: std::io::Error) -> Self {
eprintln!("io error: {error}");
AppError::InternalError
}
}
impl From<serde_json::Error> for AppError {
fn from(error: serde_json::Error) -> Self {
eprintln!("json error: {error}");
AppError::InternalError
}
}
impl From<std::num::ParseIntError> for AppError {
fn from(_error: std::num::ParseIntError) -> Self {
AppError::ValidationError("port must be a number".to_string())
}
}
pub mod errors;
use axum::{Json, Router, routing::get};
use errors::AppError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
pub name: String,
pub port: u16,
}
pub fn app() -> Router {
Router::new()
.route("/config", get(read_config))
.route("/config-broken", get(read_broken_config))
.route("/config-missing", get(read_missing_config))
}
async fn load_config() -> Result<Config, AppError> {
let text = tokio::fs::read_to_string("config.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(config)
}
async fn read_config() -> Result<Json<Config>, AppError> {
let config = load_config().await?;
Ok(Json(config))
}
async fn read_broken_config() -> Result<Json<Config>, AppError> {
let text = tokio::fs::read_to_string("broken.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(Json(config))
}
async fn read_missing_config() -> Result<Json<Config>, AppError> {
let text = tokio::fs::read_to_string("missing.json").await?;
let config: Config = serde_json::from_str(&text)?;
Ok(Json(config))
}
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
thiserror = "2.0"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the checks with these commands.
cargo check
cargo test
cargo run
cargo check confirms the conversions compile. cargo test proves the three outcomes, good file, missing file, and broken file, produce the right status and body. cargo run starts the server for the curl checks shown near the top of the page.
Summary
The single most important insight on this page is that a From implementation is a decision about meaning, not a piece of plumbing. Each one answers two questions at once. Whose fault is this failure, and what may the client know about it? The input-output and JSON conversions answer both the same way, because both failures live on the server side, so both become a generic 500 with the detail kept in the log. The number parsing conversion answers differently, because its failure lives in the input, so it becomes a 422 with a message the sender can act on.
That decision framework is the thing to carry forward. When a new error type appears in a handler, ask the two questions before writing any code. If the fault is the server's, map it to the internal variant and log the detail. If the fault is the sender's, map it to the validation variant with a short message. If the conversion would need information the error alone does not carry, leave it out of From and handle it at the call site. A small set of honest conversions keeps every handler short, keeps every response consistent, and keeps the error file as the one place where the application decides what failure means.