Skip to content

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.

A form with an error under a field and an error above the formLocal demo: the admin panel shows errors under each field and formErrors in an alert at the top of the form.

Quick start ​

rust
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()))
}
json
{ "message": "Not found.", "code": "not_found" }

The response ​

Every AppError answers JSON with message and code. The other keys appear only for one status:

KeyPresent onHolds
messageevery errora human message (see the table below)
codeevery errorthe stable code
reason409which conflict (busy, …)
errors, formErrors422messages per field, messages for the whole form
issues, formIssues422the stable code and parameters of each message, in the same order

A 422:

json
{
  "message": "The given data was invalid.",
  "code": "validation_failed",
  "errors": { "title": ["is required"] },
  "formErrors": [],
  "issues": { "title": [{ "code": "required", "params": {} }] },
  "formIssues": []
}

A 409:

json
{
  "message": "Another change to the same data is in progress. Nothing was saved; try again.",
  "code": "write_conflict",
  "reason": "busy"
}

Variants ​

AppErrorStatuscodemessage
BadRequest(detail)400bad_requestdetail, shown to the client
Unauthenticated401unauthenticatedUnauthenticated.
Forbidden403forbiddenThis action is unauthorized.
CsrfMismatch403csrf_mismatchCSRF token mismatch.
NotFound404not_found (also for records outside the user's scope)Not found.
MethodNotAllowed405method_not_allowedMethod not allowed.
Conflict { code, reason, message }409code (e.g. write_conflict)message
PayloadTooLarge413payload_too_largePayload too large.
Validation(errors)422validation_failedThe given data was invalid.
TooManyRequests { retry_after }429too_many_requests (+ Retry-After header, seconds)Too many attempts. Please try again later.
Internal(detail)500internal_errorServer error.; the detail is logged, returned only by the debug page

Helpers:

MethodDoes
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 → AppErrorFrom, 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:

rust
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_conflict with reason: "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 SQLSTATE 55P03, 40P01 and 40001; on MySQL by error numbers 1205, 1213 and 3572; 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 ​

rust
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 ​

AnswerBody
unknown path404 not_found, JSON as above
known path, other method405 method_not_allowed, JSON
request longer than http.timeout_secs (default 30)408 with an empty body
GET /healthits 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 a debug object. The panel shows it after the error's message.

The admin panel's error state: the message with the type and location, the causes, and a Copy as Markdown buttonLocal 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.

The debug page: the error's type, message and location, the source around the failing line, then the causes and the requestA handler whose ? failed on a database error (rendered by debug_page.rs in rustcms-testing).

json
{
  "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:

rust
.map_err(|err| match err {
    AppError::Internal(detail) => AppError::Internal(detail.redact(|text| *text = text.replace(&token, "***"))),
    other => other,
})

Security ​

  • BadRequest(detail) and Conflict.message are shown to the client: never put secrets, SQL or internal paths in them. Use AppError::internal for details only the logs should see.
  • NotFound is 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_conflict by its reason and the endpoint's retry contract. busy is 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.
  • CsrfMismatch concerns the admin session only: fetch a new token, do not replay the request as is.
  • Clients should read code (and reason), not message: messages may change wording.

RustCMS 0.17.0 · source cfb82fa33fab · MIT OR Apache-2.0