ValidationError variant
Learn how the AppError ValidationError variant carries a message about bad input and when a handler returns it
AppError::ValidationError is the variant a handler returns when the client sent a request the server understood but cannot accept. The title is empty, the price is negative, the username is too long. The request parsed, the route matched, and the values inside it break the rules the app enforces. The variant carries a String, and that string is the message explaining exactly what was wrong.
Where This Fits
The page about the NotFound variant covered the failure where the thing asked for does not exist. This page covers the failure where the thing sent in is wrong. The two are easy to confuse, because both are the client's doing, but they ask for different reactions. A missing book tells the client to check the id. A bad title tells the client to fix the value it sent and try again. The variant exists so the app can say the second thing clearly.
Think of a form with a red outline around the field that failed. The form does not vanish, and the page does not crash. One field is marked, and a short message next to it says what to change. ValidationError is that red outline and that message, carried from the handler to the client in a single value.
The Smallest Working Version
Start with the check itself, as a plain function. It takes a title, applies one rule, and returns either silent success or the variant with a message.
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
pub mod errors;
use errors::AppError;
pub fn check_title(title: &str) -> Result<(), AppError> {
if title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
Ok(())
}
The variant is built with the message inside the parentheses: ValidationError("title must not be empty".to_string()). The .to_string() call converts the string literal, which is a &str, into an owned String, which is what the variant holds. The variant owns its message, so the message lives as long as the error does, and the code that receives the error can hand the message to the client without borrowing anything.
Run it through a demo to see both arms:
use axum_project::check_title;
fn main() {
println!("{:?}", check_title("Dune"));
println!("{:?}", check_title(""));
println!("{:?}", check_title(" "));
}
Ok(())
Err(ValidationError("title must not be empty"))
Err(ValidationError("title must not be empty"))
The first call passes and prints Ok(()), an empty success. The second and third calls fail with the same message, because trim() strips the spaces from " " before the emptiness check, so a title of only spaces counts as empty. A title of spaces is not a title, and the check catches it by looking at the trimmed text.
The Message Is Data, Not Decoration:
The String inside ValidationError is the only variant payload in the enum, and it exists because the client needs the detail. NotFound needs no words, because the client already knows what it asked for. A validation failure needs words, because only the server knows which rule broke and how to fix it.
Using ValidationError in a Handler
A create handler reads the JSON body, checks the values, and returns the variant the moment a check fails. The conversion that turns the variant into an HTTP response lives in src/errors.rs alongside the enum, and its full explanation belongs to the page about implementing IntoResponse for AppError.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
pub mod errors;
use axum::{
Json,
routing::post,
Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
pub struct Book {
pub id: u32,
pub title: String,
}
#[derive(Deserialize)]
pub struct NewBook {
pub title: String,
}
pub fn app() -> Router {
Router::new().route("/books", post(create_book))
}
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
if input.title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
if input.title.len() > 100 {
return Err(AppError::ValidationError(
"title must be at most 100 characters".to_string(),
));
}
Ok(Json(Book {
id: 2,
title: input.title,
}))
}
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 Cargo.toml file is the same project file as the enum page, with axum, tokio, serde, and serde_json as dependencies and tower as a dev-dependency for tests.
Start the server with cargo run and post an empty title:
curl -i -X POST -H "content-type: application/json" -d '{"title":""}' http://127.0.0.1:3000/books
The response is a 422 with the message in the body:
HTTP/1.1 422 Unprocessable Entity
content-type: application/json
content-length: 35
{"error":"title must not be empty"}
Post a valid title, and the same handler answers with the created book:
curl -X POST -H "content-type: application/json" -d '{"title":"Dune"}' http://127.0.0.1:3000/books
{"id":2,"title":"Dune"}
The message the client receives is the exact string the handler put inside the variant. Nothing is added, nothing is reworded, and nothing is hidden. The handler writes the message, and the client reads it back word for word.
Working Setup:
If posting {"title":""} returns status 422 with the body {"error":"title must not be empty"}, and posting {"title":"Dune"} returns the book JSON, the variant is wired up end to end.
Understanding the Handler Line by Line
The handler has two checks, and each one teaches something different about how validation works in this design.
The Json extractor
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
Json(input) pulls the request body out and parses it as a NewBook. NewBook is a struct with one field, title, and #[derive(Deserialize)] tells serde how to fill that field from JSON. If the body is not valid JSON, or the title field is missing, the extractor fails before the handler runs, and Axum answers with its own rejection. The handler only ever sees a body that parsed, so its checks are about the values, not about the shape of the JSON. That split is what keeps the handler short: shape failures belong to the extractor, value failures belong to this variant.
The empty check
if input.title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
trim() removes spaces from both ends, is_empty() tests what is left, and return sends the error out of the handler immediately. The early return is what makes multiple checks readable: each check is a small block that either passes silently or leaves with an error, and the code below the checks can assume every rule above it passed.
The length check
if input.title.len() > 100 {
return Err(AppError::ValidationError(
"title must be at most 100 characters".to_string(),
));
}
len() counts bytes, not characters, which is fine here because the rule is a rough size limit and the message states the number. The message names the limit, 100 characters, so the client knows exactly how far over the line it went. A message that only said "title too long" would leave the client guessing, and guessing is what a good validation message prevents.
The Concept Behind Carrying the Message
The message is the difference between a failure the client can fix and a failure it can only stare at. A bare status code says something was wrong with the input. The message says which field, which rule, and what to change. That is why this variant carries a String while the other two carry nothing: the other two failures need no explanation, and this one is useless without it.
The message travels inside the error value, not beside it. The handler builds the message at the exact spot where the rule breaks, when the bad value is right there in front of it, and the message rides along through the Result, through the response conversion, and into the JSON body. Nothing needs to look the message up later, because it was written where the knowledge lived.
A message written this way is also easy to test. A test can assert the exact string, as the tests on this page do, which means a reworded message breaks a test instead of silently changing what clients see. Messages are part of the API surface, and testing them like code is what keeps them stable.
Messages Are Part of the API:
Clients parse and display these messages, and some clients match on their wording. Changing "title must not be empty" to "title is required" is a breaking change for any client that displays or checks the old text. Treat a message edit like an API edit, and update the tests that assert the exact string.
When a Handler Returns ValidationError
The rule is short: return the variant when the request was well formed and the values inside it break a rule the app enforces. The request parsed, so the shape was fine. The values failed, so the content was not.
An empty title qualifies. A title over the length limit qualifies. A negative price qualifies, because a price cannot be below zero. A start date after the end date qualifies, because the pair contradicts itself even though each date alone is valid. A username with characters the app does not allow qualifies. In each case the handler knows the rule, sees the value break it, and says so in plain words.
A missing field does not qualify, because the extractor rejects it before the handler runs. A body that is not JSON does not qualify either, for the same reason. A title that is valid but matches no book in the store is not a validation failure, it is a missing resource. A database that refuses the write is not a validation failure, it is a server-side failure. The variant is for values the handler itself judged and found wanting, and nothing else.
Writing Messages a Client Can Act On
A good validation message names the field, names the rule, and names the fix. "title must not be empty" does all three in five words: the field is the title, the rule is non-empty, and the fix is to provide one. "title must be at most 100 characters" does the same for the length rule, and the number in the message lets the client check its own input before sending it again.
A bad message hides one of those three pieces. "Invalid input" names no field, so a form with ten fields cannot highlight the right one. "Bad title" names no rule, so the client does not know whether the title was empty, too long, or full of banned characters. "Something went wrong" names nothing at all, and it is the message reserved for server-side failures, where hiding the detail is deliberate. For validation, hiding the detail is the opposite of the goal.
Keep messages short, plain, and free of internals. The client needs "title must not be empty", not "check constraint users_title_not_empty failed on insert". Database names, column names, and internal rule names belong in the server log, not in the response. The message is written for the person using the API, not for the person debugging the server.
Checking More Than One Field
A real create handler checks several fields, and the checks run in order, first failure wins. The handler below validates a book with a title and a page count, and it returns the moment any check fails.
pub mod errors;
use axum::{
Json,
routing::post,
Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
pub struct Book {
pub id: u32,
pub title: String,
pub pages: u32,
}
#[derive(Deserialize)]
pub struct NewBook {
pub title: String,
pub pages: u32,
}
pub fn app() -> Router {
Router::new().route("/books", post(create_book))
}
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
if input.title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
if input.title.len() > 100 {
return Err(AppError::ValidationError(
"title must be at most 100 characters".to_string(),
));
}
if input.pages == 0 {
return Err(AppError::ValidationError(
"pages must be at least 1".to_string(),
));
}
Ok(Json(Book {
id: 2,
title: input.title,
pages: input.pages,
}))
}
Posting {"title":"Dune","pages":0} returns 422 with {"error":"pages must be at least 1"}. Posting a body that breaks two rules at once, an empty title and zero pages, returns only the first failure, the empty title. First failure wins is a deliberate choice: it keeps the response to one message, it keeps the handler code linear, and it matches how most clients handle errors, by fixing one thing and resubmitting. Reporting every broken rule at once needs a different body shape, with one message per field, and that shape belongs to the page about field errors.
Building Messages With format!
Some messages need a number from the input, like the limit that was exceeded or the value that was rejected. format! builds those messages from a template and the values that fill it.
if title.len() > 100 {
return Err(AppError::ValidationError(format!(
"title must be at most {} characters",
100
)));
}
format! works like println! except it returns a String instead of printing one. The {} placeholder takes the next argument, 100, and writes it into the message. The result is the same string the literal version produced, "title must be at most 100 characters", and a test asserting that exact string passes either way. Use format! when the message must include a value that changes, like a limit read from configuration or the length the client actually sent. Use a plain literal when the message never changes, because a literal is shorter and easier to read.
Moving Checks Into a Helper Function
Checks written inline in the handler get in the way once there are more than two of them. A helper function that returns Result<(), AppError> keeps the handler short and lets several handlers share the same rules.
pub mod errors;
use errors::AppError;
pub fn check_title(title: &str) -> Result<(), AppError> {
if title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
if title.len() > 100 {
return Err(AppError::ValidationError(
"title must be at most 100 characters".to_string(),
));
}
Ok(())
}
The handler then calls the helper with the ? operator, which returns the error from the handler immediately when the helper fails, and continues when it succeeds:
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
check_title(&input.title)?;
Ok(Json(Book {
id: 2,
title: input.title,
}))
}
The ? operator is shorthand for "if this is an Err, return it from my function right now". It only works because the helper and the handler return the same error type, AppError. That shared type is what makes the operator available, and it is another reason the enum is shared across the whole app instead of invented per handler.
How a Bad Title Flows
The diagram below follows one bad create request from the body to the response.
POST /books {"title":""}
|
v
Json parses the body, title is ""
|
v
Handler checks the title, trim leaves ""
|
v
Handler returns Err(ValidationError("title must not be empty"))
|
v
IntoResponse turns the variant into a response
|
v
422 Unprocessable Entity, {"error":"title must not be empty"}
The message is written once, in the handler, and it survives the whole trip untouched. Nothing along the way rewords it, truncates it, or wraps it in another structure. That is why the message the client sees is the message the handler wrote.
Testing ValidationError
The tests post a bad body and a good body through the router with oneshot, and they assert the exact status and the exact message.
use axum::{
body::Body,
http::{Request, StatusCode},
};
use axum_project::app;
use tower::ServiceExt;
async fn body_text(response: axum::response::Response) -> String {
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
String::from_utf8(bytes.to_vec()).unwrap()
}
#[tokio::test]
async fn empty_title_returns_422_with_message() {
let response = app()
.oneshot(
Request::builder()
.uri("/books")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(r#"{"title":""}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body_text(response).await,
r#"{"error":"title must not be empty"}"#
);
}
#[tokio::test]
async fn long_title_returns_422_with_message() {
let long = "a".repeat(101);
let payload = format!(r#"{{"title":"{}"}}"#, long);
let response = app()
.oneshot(
Request::builder()
.uri("/books")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(payload))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(
body_text(response).await,
r#"{"error":"title must be at most 100 characters"}"#
);
}
#[tokio::test]
async fn valid_title_creates_the_book() {
let response = app()
.oneshot(
Request::builder()
.uri("/books")
.method("POST")
.header("content-type", "application/json")
.body(Body::from(r#"{"title":"Dune"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
body_text(response).await,
r#"{"id":2,"title":"Dune"}"#
);
}
The long-title test builds its payload with "a".repeat(101), which produces a string of 101 a characters, one past the limit. That boundary matters: a title of exactly 100 characters must pass, and a title of 101 must fail, and the test pins the failing side. All three tests passed against the scratch project, and the live server returned the same 422 body through curl. Run them with cargo test and expect:
test empty_title_returns_422_with_message ... ok
test long_title_returns_422_with_message ... ok
test valid_title_creates_the_book ... ok
The body_text helper is a small async function that reads the response body and turns it into a String, so the three tests can share the reading logic instead of repeating it. The .method("POST") call sets the request method, and the content-type header tells the Json extractor the body is JSON.
Common Beginner Mistakes
Returning the message without the variant
// Wrong - a bare String is not the shared error type
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, String> {
if input.title.trim().is_empty() {
return Err("title must not be empty".to_string());
}
Ok(Json(Book { id: 2, title: input.title }))
}
This compiles, and it breaks the design. The handler now returns a different error type from every other handler, the response conversion for AppError never sees it, and the client gets a different body shape for this failure than for the others. The fix is to return AppError::ValidationError with the message inside, so the handler shares the type, the conversion, and the body shape with the rest of the app.
A String Error Bypasses the Whole Design:
Returning Result<Json<Book>, String> means Axum turns the string into a plain-text 500 response, because a String error has no status mapping of its own. A validation failure would then arrive as a server error with the wrong status and the wrong body, and the client would treat a fixable input problem as a broken server.
Validating after writing to the store
// Wrong - the bad row is already stored when the check runs
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
let book = store_book(&input);
if input.title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
Ok(Json(book))
}
Validation runs before any side effect. If the check runs after the write, the bad data is already in the store when the error returns, and the client believes the create failed while the store holds a row with an empty title. Check first, write second, and never let a failed request leave a trace behind.
Forgetting trim and accepting spaces as a title
// Wrong - " " passes the check and becomes a book title
if input.title.is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
is_empty() on " " returns false, because the string has three characters in it. The book is created with a title of spaces, which displays as nothing everywhere it appears. The fix is input.title.trim().is_empty(), which strips the spaces first and then tests what remains.
Using ValidationError for a missing resource
// Wrong - a book that does not exist is not bad input
async fn get_book(Path(id): Path<u32>) -> Result<Json<Book>, AppError> {
if id != 1 {
return Err(AppError::ValidationError("book not found".to_string()));
}
Ok(Json(Book { id: 1, title: "The Rust Book".to_string() }))
}
The client sent a valid id, and the store has no such book. The input was fine, the lookup missed, and the right variant is NotFound. Returning ValidationError tells the client its input was wrong and invites it to "fix" an id that was never broken. Keep the two failures apart, because each one tells the client to do something different.
Final Complete Example
Here is everything from this page in one place: the shared enum with its response conversion, the create handler with two checks, and the helper the handler could use instead.
use axum::{
Json,
http::StatusCode,
response::{IntoResponse, Response},
};
use serde_json::json;
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::NotFound => (StatusCode::NOT_FOUND, "resource not found".to_string()),
AppError::ValidationError(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
AppError::InternalError => (
StatusCode::INTERNAL_SERVER_ERROR,
"something went wrong".to_string(),
),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
pub mod errors;
use axum::{
Json,
routing::post,
Router,
};
use errors::AppError;
use serde::{Deserialize, Serialize};
#[derive(Serialize)]
pub struct Book {
pub id: u32,
pub title: String,
}
#[derive(Deserialize)]
pub struct NewBook {
pub title: String,
}
pub fn app() -> Router {
Router::new().route("/books", post(create_book))
}
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
check_title(&input.title)?;
Ok(Json(Book {
id: 2,
title: input.title,
}))
}
pub fn check_title(title: &str) -> Result<(), AppError> {
if title.trim().is_empty() {
return Err(AppError::ValidationError(
"title must not be empty".to_string(),
));
}
if title.len() > 100 {
return Err(AppError::ValidationError(
"title must be at most 100 characters".to_string(),
));
}
Ok(())
}
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();
}
Run the server, post an empty title, and the answer is 422 with {"error":"title must not be empty"}. Post a title over 100 characters, and the answer is 422 with the length message. Post a good title, and the book comes back.
Summary
ValidationError is the variant that talks back to the client in its own words. The decision framework is a short test applied at the point where the handler holds a parsed value: did the request parse, did the value break a rule this app enforces, and can the client fix it by changing what it sent. When all three hold, return the variant with a message that names the field, the rule, and the fix. The deeper point is that validation is a conversation, not a rejection. The server understood the request, it knows exactly what is wrong with it, and it says so in the same breath as it refuses it. A client that receives that message never has to guess, and a client that never has to guess is a client that can fix the problem on the first retry.