Status code mapping
Learn which HTTP status code each AppError variant maps to and why NotFound is 404, ValidationError is 422, and InternalError is 500
The status code mapping is the table that says which HTTP status each AppError variant becomes: NotFound becomes 404, ValidationError becomes 422, and InternalError becomes 500. The mapping lives inside the IntoResponse implementation, one arm per variant, and it is the first thing a client reads in every error response. The body explains, but the status decides, because clients, caches, and monitoring tools all branch on the number before they ever parse the words.
Where This Fits
The page about the AppError IntoResponse implementation showed the whole conversion, the match that picks a status and a message and the tuple that builds the response. This page takes one column of that match, the status column, and explains why each row holds the number it holds. The implementation is the mechanism, and this page is the reasoning behind the numbers in it.
Think of traffic lights. The colour is not the whole message, it is the part every driver reads first, from a distance, without reading any sign. Red means stop, green means go, and the meaning is shared by everyone on the road. Status codes are the colours of HTTP, and the mapping is the agreement about which colour each failure gets.
The Smallest Working Version
The mapping is three lines inside the implementation, and it helps to see them on their own before the rest of the conversion crowds them out.
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()
}
}
StatusCode is a type from the http crate, which Axum re-exports as axum::http. Its associated constants name the codes: NOT_FOUND is 404, UNPROCESSABLE_ENTITY is 422, and INTERNAL_SERVER_ERROR is 500. Using the named constants instead of raw numbers is what keeps the mapping readable. StatusCode::NOT_FOUND says what the code means, and 404 on its own says only what the code is. A reader who has never memorised the numbers can still read the mapping.
The mapping as a table:
| Variant | Status code | Number | Meaning in plain words |
|---|---|---|---|
NotFound | StatusCode::NOT_FOUND | 404 | The thing asked for does not exist |
ValidationError | StatusCode::UNPROCESSABLE_ENTITY | 422 | The input was understood but breaks a rule |
InternalError | StatusCode::INTERNAL_SERVER_ERROR | 500 | Something failed on the server side |
Run the server from the earlier pages and check all three numbers with curl:
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3000/books/99
curl -s -o /dev/null -w "%{http_code}\n" -X POST -H "content-type: application/json" -d '{"title":""}' http://127.0.0.1:3000/books
curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3000/boom
The -o /dev/null flag throws the body away, and -w "%{http_code}\n" prints only the status number. The three lines of output are the whole mapping, confirmed live:
404
422
500
Working Setup:
If the three curl commands print 404, 422, and 500 in that order, the mapping is wired up end to end.
What the First Digit Means
HTTP status codes have three digits, and the first digit names the class. Codes starting with 2 mean success. Codes starting with 4 mean the client made an error. Codes starting with 5 mean the server made an error. That single digit is the most important part of the code, because it answers the question every client asks first: whose fault is this, and can I fix it by changing what I sent.
NotFound and ValidationError are both 4xx codes, because both failures belong to the client. The client asked for a thing that is not there, or sent values that break the rules. In both cases the server did its job, and changing the request is the only fix. InternalError is a 5xx code, because the failure belongs to the server. The client did nothing wrong, and no change to the request will help. A client that retries a 500 later may succeed, because the server may have recovered. A client that retries a 404 or a 422 with the same request will fail the same way, because the request itself is the problem.
The class digit is also what monitoring tools count. A dashboard that graphs 4xx against 5xx is graphing client problems against server problems, and an operator reads a spike in 5xx as "our side is broken" and a spike in 4xx as "clients are sending bad requests". A mapping that puts a server failure in the 4xx class would hide a broken server behind a client-error graph, and a mapping that puts a client failure in the 5xx class would wake the operator for a typo in a request. Getting the first digit right is what keeps the graphs honest.
Why NotFound Is 404
404 is the code that means the server understood the request and the specific resource does not exist. The route matched, the id parsed, the store was checked, and there was nothing there. Every part of that sentence is required for the code to apply, and it matches the NotFound rule exactly: the route matched, the input parsed, the lookup ran, and the store had no row.
The code also carries a useful property for clients: it is safe to cache. A client or a proxy that caches a 404 for /books/99 will not ask again for a while, which is correct behaviour for a thing that does not exist. And it is safe to stop retrying, because the same request will keep failing until the resource is created. A 404 is a final answer for this request, not a "try again later" answer.
The common alternatives are all worse. A 200 with an empty body lies about success, as the NotFound page showed. A 400 says the request itself was malformed, which is not true, because the request was well formed and only the id had no match. A 500 says the server broke, which is not true either, because the server worked correctly and answered a factual question. 404 is the code that describes the situation without blaming the wrong side.
Why ValidationError Is 422
422, Unprocessable Entity, is the code that means the server understood the request, including its syntax and its content type, but cannot process the values inside it. The JSON parsed, the fields were present, and the values break the rules. That description matches the validation rule exactly: the request was well formed, and the values inside it were not acceptable.
The number needs a comparison to earn its place, because 400 is the code most beginners reach for first. 400, Bad Request, means the request itself was malformed, the JSON did not parse, or the syntax was broken. In this design, those failures never reach the handler, because the extractor rejects them before the handler runs. By the time the handler sees the values, the syntax is fine, so 400 would describe a problem that does not exist. 422 describes the problem that does exist: valid syntax, invalid content.
The distinction matters to clients. A client that receives a 400 assumes its request was broken at the syntax level and may try to fix its JSON encoding. A client that receives a 422 knows the JSON was fine and the values were wrong, so it shows the message next to the field and lets the user fix the value. The two codes send the client down two different paths, and 422 sends it down the right one.
422 Has a Longer Name Than Its Number Suggests:
The constant is UNPROCESSABLE_ENTITY, and the official reason phrase for 422 in HTTP is "Unprocessable Content" in newer specifications and "Unprocessable Entity" in older ones. The number is what clients read, and the constant name is what your code reads. Both refer to the same code, and the number is the part that must be right.
Why InternalError Is 500
500, Internal Server Error, is the code that means the server hit a condition it did not expect and cannot say more about. The request was fine, the input was fine, and the failure belongs to the server side. That is the InternalError rule word for word. It is also the most generic code in the 5xx class, which fits a variant that deliberately hides the cause: the code says the server failed, and the body says nothing more, because the details stay in the log.
The alternatives fail the same test as before. A 400 would blame the client for a server failure. A 404 would claim the resource does not exist, when the truth is the server could not check. A 503, Service Unavailable, means something more specific: the server is temporarily unable to handle the request, usually because it is overloaded or down for maintenance, and it often carries a Retry-After header telling the client when to come back. A single failed database query is not an overloaded server, so 503 overpromises a recovery the app cannot guarantee. 500 is the honest generic answer for a server-side failure with no more specific code that fits.
A 500 also has the right retry semantics. A client that receives a 500 knows the request itself was fine, so retrying the same request later is reasonable. A client that receives a 422 knows retrying the same request is pointless. The code tells the client whether to try again or to change the request, and 500 gives the correct advice for a server failure.
The Mapping in the Match
Each arm of the match in the implementation is one row of the table, and the arm is the only place where the variant and its code meet. That single meeting point is what keeps the mapping consistent.
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(),
),
};
The status and the message are chosen together in each arm, because they belong together: the code says the class of the failure, and the message says the detail. NotFound pairs 404 with a fixed message, because the message never changes. ValidationError pairs 422 with the message from the variant, because the message is the point of the failure. InternalError pairs 500 with a fixed generic message, because the detail must not travel. If a new variant is added to the enum, the compiler demands a new arm here, and the developer adding the variant must choose its code at the same moment. The mapping cannot drift out of date, because the build fails until it is updated.
One Arm, One Decision:
The status for a variant is decided in exactly one arm of one match. If a handler ever builds its own status for the same variant, the app has two mappings that can disagree. Keep the decision in the match, and let handlers only choose the variant.
Reading the Code From a Status Alone
A client that only reads the status code can still act correctly, because the mapping is designed so the number alone carries the decision. The table below is the client-side reading of the three codes.
| Status | What the client knows | What the client should do |
|---|---|---|
| 404 | The item does not exist | Stop, show a missing message, check the id |
| 422 | The values break a rule | Show the message, fix the input, resubmit |
| 500 | The server failed | Retry later, or contact support |
That table is the reason the mapping is worth a page of its own. The body adds the words, but the number carries the decision, and a client that respects the number behaves correctly even before it parses a single byte of JSON. A mapping that gets the numbers wrong teaches every client the wrong behaviour, no matter how good the messages are.
Factoring the Mapping Into a Helper Method
The mapping can also live in a small method on the enum, with the implementation calling it. The behaviour is identical, and the shape fits when other code needs the status without building a full response, for example a log line that records the code.
#[derive(Debug)]
pub enum AppError {
NotFound,
ValidationError(String),
InternalError,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
AppError::ValidationError(_) => StatusCode::UNPROCESSABLE_ENTITY,
AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
The method takes &self, a reference, because it only reads the variant and does not need to own it. The ValidationError(_) pattern ignores the inner message, because the status does not depend on the words. The method was compile-checked and run in a scratch project, where it returned 404, 422, and 500 for the three variants. The implementation can then call it:
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let status = self.status_code();
let message = match self {
AppError::NotFound => "resource not found".to_string(),
AppError::ValidationError(message) => message,
AppError::InternalError => "something went wrong".to_string(),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
This form matches on self twice, once by reference inside the method and once by value for the message, which is fine because the reference borrow ends when the method returns. The canonical form in the earlier pages keeps both decisions in one match, and it is the better default, because one match means one place to update when a variant is added. Use the helper form only when something else in the codebase genuinely needs the status on its own. Two mappings, even identical ones, are two places that can drift apart.
How the Codes Flow
The diagram below follows the three variants through the same implementation to their three codes.
AppError::NotFound
|
v
match arm picks StatusCode::NOT_FOUND
|
v
404 Not Found
AppError::ValidationError(message)
|
v
match arm picks StatusCode::UNPROCESSABLE_ENTITY
|
v
422 Unprocessable Entity
AppError::InternalError
|
v
match arm picks StatusCode::INTERNAL_SERVER_ERROR
|
v
500 Internal Server Error
Three variants enter, three codes leave, and nothing else in the app touches a status code for these failures. The mapping is a pure function of the variant, and that purity is what makes it easy to test, easy to document, and easy to trust.
Testing the Mapping
The tests call into_response on each variant and assert the status, and they also check the full round trip through the router. They pin the numbers down so a future edit that swaps two codes breaks a test instead of silently changing the API.
use axum::{
body::Body,
http::{Request, StatusCode},
response::IntoResponse,
};
use axum_project::{app, errors::AppError};
use tower::ServiceExt;
#[test]
fn mapping_gives_each_variant_its_code() {
assert_eq!(
AppError::NotFound.into_response().status(),
StatusCode::NOT_FOUND
);
assert_eq!(
AppError::ValidationError("title must not be empty".to_string())
.into_response()
.status(),
StatusCode::UNPROCESSABLE_ENTITY
);
assert_eq!(
AppError::InternalError.into_response().status(),
StatusCode::INTERNAL_SERVER_ERROR
);
}
#[test]
fn codes_are_404_422_and_500() {
assert_eq!(StatusCode::NOT_FOUND.as_u16(), 404);
assert_eq!(StatusCode::UNPROCESSABLE_ENTITY.as_u16(), 422);
assert_eq!(StatusCode::INTERNAL_SERVER_ERROR.as_u16(), 500);
}
#[tokio::test]
async fn router_returns_the_mapped_codes() {
let not_found = app()
.oneshot(
Request::builder()
.uri("/books/99")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(not_found.status(), StatusCode::NOT_FOUND);
let internal = app()
.oneshot(
Request::builder()
.uri("/boom")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(internal.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
The as_u16() method returns the numeric code, which lets the test assert the numbers themselves rather than only the named constants. A test that only compared constants would pass even if a constant were somehow wrong, which cannot happen in practice, but asserting the numbers documents the contract in the form clients actually see. All three tests passed against the scratch project, and the three curl commands at the start of this page printed 404, 422, and 500 from the live server. Run them with cargo test and expect:
test mapping_gives_each_variant_its_code ... ok
test codes_are_404_422_and_500 ... ok
test router_returns_the_mapped_codes ... ok
Common Beginner Mistakes
Using 400 for validation failures
// Wrong - 400 means the request was malformed, and it was not
AppError::ValidationError(message) => (StatusCode::BAD_REQUEST, message),
The JSON parsed, the fields were present, and the values broke a rule. 400 describes a malformed request, which is a different failure, one the extractor already handles before the handler runs. Using 400 for validation tells the client to fix its JSON encoding when the JSON was fine. The fix is StatusCode::UNPROCESSABLE_ENTITY, which describes the failure that actually happened.
400 and 422 Are Not Interchangeable:
A client that receives 400 checks its request syntax. A client that receives 422 checks its field values. Sending the wrong code sends the client to fix the wrong thing, and the user ends up staring at a form that looks correct while the server keeps rejecting it.
Using 200 for a missing resource
// Wrong - success status for a failure, handled by returning Ok
async fn get_book(Path(id): Path<u32>) -> Json<Option<Book>> {
if id == 1 {
Json(Some(Book { id: 1, title: "The Rust Book".to_string() }))
} else {
Json(None)
}
}
The same mistake from the NotFound page, seen from the mapping side: the status code is the primary signal, and a 200 for a missing resource corrupts every consumer that reads the code first, which is every consumer. The fix is the Result return type with Err(AppError::NotFound), which maps to 404.
Using 500 for a client failure
// Wrong - a server code for a client problem
AppError::ValidationError(message) => (StatusCode::INTERNAL_SERVER_ERROR, message),
A validation failure is the client's doing, and a 500 tells the operator the server broke. The operator investigates, finds nothing wrong with the server, and the real cause, a bad title, hides in a server-error graph. It also tells the client to retry later, which will fail the same way, because the input has not changed. Keep the first digit honest: 4xx for the client's failures, 5xx for the server's.
Hard-coding numbers instead of named constants
// Wrong - the number carries no meaning on its own
use axum::http::StatusCode;
let status = StatusCode::from_u16(404).unwrap();
StatusCode::from_u16 builds a code from a raw number at runtime, and it can fail, which is why it returns a Result that needs unwrapping. The named constant StatusCode::NOT_FOUND cannot fail, cannot be mistyped as 440, and reads as what it means. Use the constants, and let the numbers appear only in tests that assert the contract.
Final Complete Example
Here is everything from this page in one place: the enum, the implementation with its three-row mapping, the three handlers that exercise it, and the curl commands that confirm the numbers.
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,
extract::Path,
routing::{get, 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/{id}", get(get_book))
.route("/books", post(create_book))
.route("/boom", get(boom))
}
async fn get_book(Path(id): Path<u32>) -> Result<Json<Book>, AppError> {
if id == 1 {
Ok(Json(Book {
id: 1,
title: "The Rust Book".to_string(),
}))
} else {
Err(AppError::NotFound)
}
}
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(),
));
}
Ok(Json(Book {
id: 2,
title: input.title,
}))
}
async fn boom() -> Result<&'static str, AppError> {
Err(AppError::InternalError)
}
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 and the three curl commands from the start of this page, and the output is 404, 422, and 500. Run cargo test, and the mapping tests pass.
Summary
The mapping is a three-row table, and its power comes from what the first digit of each row promises. 404 and 422 promise the client that the request was the problem and that changing it is the fix, with 404 for a thing that is not there and 422 for values that break a rule. 500 promises the client that the server was the problem and that retrying later is reasonable. The decision framework for any future variant is a single question: who can fix this, the client or the server. When the client can fix it, the code starts with 4, and the choice between 404 and 422 turns on whether the request was malformed or merely unacceptable. When only the server can fix it, the code starts with 5, and 500 is the honest generic answer. Keep the mapping in one match, test the numbers, and the status line will keep telling the truth even as the app grows.