Errors
Handlers return AppResult<T> (Result<T, AppError>). An AppError becomes a JSON response with a status, a human message and a stable code, so clients can branch on the code and show the message. Use it for every expected failure: not found, not allowed, invalid input, a write that must be retried.
Local demo: the admin panel shows errors under each field and formErrors in an alert at the top of the form.
Quick start
pub async fn show(State(app): State<AppState>, Path(id): Path<i64>) -> AppResult<Json<PostJson>> {
let post = post::Entity::find_by_id(id)
.one(app.db())
.await? // a database error: 500, or 409 when it can be retried
.ok_or(AppError::NotFound)?; // no row: 404
Ok(Json(post.into()))
}{ "message": "Not found.", "code": "not_found" }The response
Every AppError answers JSON with message and code. The other keys appear only for one status:
| Key | Present on | Holds |
|---|---|---|
message | every error | a human message (see the table below) |
code | every error | the stable code |
reason | 409 | which conflict (busy, …) |
errors, formErrors | 422 | messages per field, messages for the whole form |
issues, formIssues | 422 | the stable code and parameters of each message, in the same order |
A 422:
{
"message": "The given data was invalid.",
"code": "validation_failed",
"errors": { "title": ["is required"] },
"formErrors": [],
"issues": { "title": [{ "code": "required", "params": {} }] },
"formIssues": []
}A 409:
{
"message": "Another change to the same data is in progress. Nothing was saved; try again.",
"code": "write_conflict",
"reason": "busy"
}Variants
AppError | Status | code | message |
|---|---|---|---|
BadRequest(detail) | 400 | bad_request | detail, shown to the client |
Unauthenticated | 401 | unauthenticated | Unauthenticated. |
Forbidden | 403 | forbidden | This action is unauthorized. |
CsrfMismatch | 403 | csrf_mismatch | CSRF token mismatch. |
NotFound | 404 | not_found (also for records outside the user's scope) | Not found. |
MethodNotAllowed | 405 | method_not_allowed | Method not allowed. |
Conflict { code, reason, message } | 409 | code (e.g. write_conflict) | message |
PayloadTooLarge | 413 | payload_too_large | Payload too large. |
Validation(errors) | 422 | validation_failed | The given data was invalid. |
TooManyRequests { retry_after } | 429 | too_many_requests (+ Retry-After header, seconds) | Too many attempts. Please try again later. |
Internal(detail) | 500 | internal_error | Server error.; the detail is logged, returned only by the debug page |
Helpers:
| Method | Does |
|---|---|
AppError::internal(err) | wraps anything that implements Display as Internal (logged, 500), recording the error's type and where it was called |
AppError::internal_error(err) | the same for a std::error::Error, also keeping its source() chain as causes |
AppError::Internal("…".into()) | a message only (an InternalError from a &str or String) |
error.status() | the HTTP status |
error.code() | the stable code |
ValidationErrors → AppError | From, so Err(errors.into()) or errors.into_result()? |
All top-level codes, including those the framework uses for its own 409s, are listed in Error codes.
Your own conflicts
Conflict takes three &'static str: a code and reason clients can branch on, and a message shown as written (it is not translated). Use it when a request is valid but cannot apply now:
return Err(AppError::Conflict {
code: "order_shipped",
reason: "shipped",
message: "This order has shipped and can no longer be changed.",
});Database errors
? converts a sea_orm::DbErr:
A write rolled back because of other writers becomes a 409
write_conflictwithreason: "busy": the statement that failed was not applied. This covers lock wait timeouts, deadlocks, serialization failures and a busy SQLite database (database is locked). On PostgreSQL it is decided by SQLSTATE55P03,40P01and40001; on MySQL by error numbers1205,1213and3572; otherwise by the message.The conversion only classifies the error: it does not roll back what the handler wrote before the failing statement. In custom handlers, use a transaction or idempotency to make retrying the whole request safe.
Anything else becomes a 500
internal_error; the database message is logged, and returned only by the debug page.
A missing row is not an error for SeaORM (one() returns None): turn it into AppError::NotFound yourself, as in the quick start.
Validation errors
let mut errors = ValidationErrors::new();
errors.add("email", "must be a valid email address");
errors.add_form("This was changed by someone else meanwhile. Reload and try again.");
errors.into_result()?; // Ok(()) when empty
return Err(ValidationErrors::field("slug", "has already been taken").into());errors holds messages per field, formErrors messages for the whole form. issues and formIssues carry, in the same order, the stable code and parameters of each message, for clients that translate them; see Error codes. A message that follows no template gets the code custom with {"message": …}. In Rust, errors.issues() and errors.form_issues() return them as rustcms::i18n::Issue values (code, params); Issue::of(message) gives the issue of one message.
Framework-generated responses
| Answer | Body |
|---|---|
| unknown path | 404 not_found, JSON as above |
| known path, other method | 405 method_not_allowed, JSON |
request longer than http.timeout_secs (default 30) | 408 with an empty body |
GET /health | its own body: 200 {"status":"ok","database":"ok"} or 503 {"status":"degraded","database":"unavailable"} |
Handlers can call rustcms::http::request_deadline() to know when the 408 will cut the request off, and finish optional work before it.
A panic in a handler (or in a guard or middleware) answers the standard 500 ({"message": "Server error.", "code": "internal_error"}), logged as internal error: handler panicked in the request's span (the panic's message is not logged there nor sent, except by the debug page; Rust's panic hook prints it to stderr, and the request's trace records the 500); the connection stays usable. A stream that has already answered (server-sent events) cannot become a 500: the panic ends that stream. Prefer returning AppError::internal: a panic says nothing to the caller and can leave shared state half-updated.
The debug page
While you develop, a 500 can say what failed and where, without opening the logs. With APP_DEBUG=true and APP_ENV=local (a new .env has both), a request from the same machine that ends in AppError::Internal or a panic gets:
- in a browser (a page navigation): a page with the error's type, its message, where it happened with the source lines around it (the line marked), the causes, and the request: method, URL, a few headers, the matched route, the request id;
- from
fetch, the admin panel or an API client: the usual JSON with adebugobject. The panel shows it after the error's message.
Local demo: a list whose query failed, as the panel shows it with a debug server.
Both have a Copy as Markdown button: the error, where it happened, the source lines (the failing one marked >), the causes and the request, ready to paste into an issue or an AI assistant.
A handler whose ? failed on a database error (rendered by debug_page.rs in rustcms-testing).
{
"message": "Server error.",
"code": "internal_error",
"debug": {
"type": "sea_orm::error::DbErr",
"message": "Query Error: no such table: posts",
"location": "src/http/posts.rs:42",
"causes": ["no such table: posts"],
"panic": false
}
}Where it happened. ? and AppError::internal(e) record their own line. A function path such as .map_err(AppError::internal) cannot (Rust records the standard library's line), so the page also keeps a backtrace and shows the first frame in your project's files. Backtraces need line tables: the default cargo run profile has them; with CARGO_PROFILE_DEV_DEBUG=0 only ? and closures keep a location. A panic shows the panic's own line. When the page cannot tell which panic it was (the same message panicked twice, or a spawned task's panic was resumed with resume_unwind), it shows no location rather than a wrong one.
What it hides. Headers are shown from a short list (accept, host, user-agent, content-type, sec-fetch-*, x-request-id, …): never cookies, authorization, CSRF tokens or your own API key headers. Query values are replaced by …. The request body is never shown, nor copied by the button. The page runs one script, its own (allowed by its hash): the copied text sits escaped in the page, never in the script. Source is read only from .rs files of your project (the directory serve started in, when it holds a Cargo.toml; never / or your home directory) and of Cargo's registry, at most 1 MB, without following links. Messages and causes are cut at 4,000 characters, after redact has run. The page has its own strict Content-Security-Policy and Cache-Control: no-store. Messages, causes and source lines can still quote data: it is a tool for your machine.
From the same machine means: the connection comes from a loopback address, the request names a local host (localhost, *.localhost, 127.0.0.1, [::1], or the host of APP_URL; one Host, no user info), and it carries no proxy header (Forwarded, Via, X-Forwarded-*, X-Real-IP, …), even from a trusted proxy: a proxy on your machine may forward anyone. So a tunnel that shares your local server (ngrok, cloudflared) and a web page that rebinds its own name to 127.0.0.1 get the usual answer.
When it is off (any other environment, APP_DEBUG=false, a client that is not on the same machine, or no client address known), every answer is the one described above, byte for byte. With APP_DEBUG=true and APP_ENV=production, serve logs a warning and the page stays off.
It covers AppError::Internal and caught panics: the 408 of a request timeout, the 503 of /health, responses your code builds by hand and errors after a stream has started are not diagnosed.
To hide secrets a message may quote before it is logged or shown, rewrite the message and every cause with InternalError::redact:
.map_err(|err| match err {
AppError::Internal(detail) => AppError::Internal(detail.redact(|text| *text = text.replace(&token, "***"))),
other => other,
})Security
BadRequest(detail)andConflict.messageare shown to the client: never put secrets, SQL or internal paths in them. UseAppError::internalfor details only the logs should see.NotFoundis also the answer for records outside the caller's scope, so a client cannot tell a hidden record from a missing one. Keep that rule in your own handlers.
See Authorization.
Pitfalls
- Handle a 409
write_conflictby itsreasonand the endpoint's retry contract.busyis meant to be retried.receipt_expired(the admin API's idempotent writes) means the earlier request with this key is no longer known and may have been committed: reload and check the earlier result before trying again. Do not retry a 500 blindly. CsrfMismatchconcerns the admin session only: fetch a new token, do not replay the request as is.- Clients should read
code(andreason), notmessage: messages may change wording.