dust

Error Handling

Introduction

When you create a new dust-framework project, error handling is already configured for you. Whenever a handler returns an error, such as when a requested post doesn't exist or a database query fails, dust-framework converts it into an HTTP response: JSON for API clients and an error page for browsers. When an error is a server failure, dust-framework also logs it so you can investigate what went wrong.

Whenever you need to customize how your application reports or renders errors, configure the error handler with with_errors in src/app.rs.

An error travels through the same stages whether it comes from an extractor, a handler, or your own code:

  1. The failing code returns an error, or aborts with a status.
  2. dust-framework assigns an HTTP status, such as 500 when the error has none.
  3. A failure is logged and sent to your reporters; an expected outcome is not.
  4. Your renderers get a chance to build a response, then dust-framework's default renderer runs.
  5. Your responder may adjust the final response before it is sent.

Debug mode

The APP_DEBUG environment variable controls how much detail dust-framework exposes when a server failure occurs. When APP_DEBUG=true, browsers receive a detailed debug page showing the error, where it happened, its chain of causes, and the incoming request, while JSON responses include the error's type, file, and line.

When APP_DEBUG=false, dust-framework replaces failure messages with "Server Error" so internal messages written for your logs never leak to users. The only exception is a failure raised intentionally for clients with abort_with, such as dust::abort_with(503, "We're upgrading. Back in a minute."), which includes that message in JSON responses.

New applications enable debug mode in .env for local development:

ini
APP_DEBUG=true

[!WARNING] Always set APP_DEBUG to false in production. The debug page exposes stack traces, request data, and internal error messages to your users.

Returning errors

Handlers and middleware that can fail return dust::Result. Using ?, any type that implements std::error::Error converts automatically into dust::Error, as does an anyhow::Error from a library. Unless the error specifies a status code, dust-framework responds with 500 Internal Server Error:

rust
use dust::prelude::*;use crate::models::User;pub async fn show(Params(id): Params<i64>) -> dust::Result<Json<User>> {    let user = User::find_or_fail(id).await?;    Ok(Json(user))}

If the database query fails, find_or_fail returns a 500 error. If no user matches the given ID, it returns a 404 because ModelNotFound carries a status of 404.

When you want to return a one-off error without defining a custom error type, create one from a message with dust::Error::msg:

rust
pub fn header_row(contents: &str) -> dust::Result<&str> {    let Some(header) = contents.lines().next() else {        return Err(dust::Error::msg("the import file has no header row"));    };    Ok(header)}

dust-framework treats this error as a 500 failure, logging the message while showing "Server Error" to users outside debug mode. If you want the message returned to the client instead, use dust::abort_with(500, message).

Defining your own errors

An error type is any struct or enum that implements std::error::Error. New applications include the thiserror crate, which derives the implementation for you. The #[error("...")] attribute defines the error's message and may interpolate fields by name or position:

rust
#[derive(Debug, thiserror::Error)]pub enum PaymentError {    #[error("The card was declined: {reason}")]    Declined { reason: String },    #[error("The amount {0} is below the minimum")]    BelowMinimum(u64),    #[error("The receipt couldn't be saved")]    Receipt(#[from] std::io::Error),}

Adding #[from] lets ? convert the inner error into your variant automatically, so an std::io::Error becomes PaymentError::Receipt and keeps the original dust::Error as its cause:

rust
pub fn save_receipt(path: &str, contents: &str) -> Result<(), PaymentError> {    std::fs::write(path, contents)?;    Ok(())}

Errors with their own status

To associate an HTTP status code with an error type, such as 409 Conflict for a double booking, derive Status and add #[status(..)]. Returning that error from a handler with ? then responds with that status:

rust
use dust::errors::Status;#[derive(Debug, thiserror::Error, Status)]#[error("This time slot is already booked")]#[status(409)]pub struct BookingConflict;

On an enum, you may give each variant its own status. Any variant without a #[status(..)] attribute defaults to 500:

rust
use dust::errors::Status;#[derive(Debug, thiserror::Error, Status)]pub enum PaymentError {    #[error("The card was declined: {reason}")]    #[status(402)]    Declined { reason: String },    #[error("The amount {0} is below the minimum")]    #[status(422)]    BelowMinimum(u64),    #[error("The receipt couldn't be saved")]    Receipt(#[from] std::io::Error),}

The status may be a numeric code such as 402 or a StatusCode constant such as StatusCode::PAYMENT_REQUIRED.

You can't derive Status on an error type defined in another crate. Instead, map its status inside with_errors in src/app.rs. Mapping a type there also overrides a derived status, such as one from a package:

rust
use dust::prelude::*;Application::configure()    .with_errors(|errors, _| {        errors.status::<dust::db::sqlx::Error>(503);    })

To assign a status to a single error at the point you return it, wrap it with dust::Error::new:

rust
return Err(dust::Error::new(409, BookingConflict));

Adding context

Low-level errors such as "No such file or directory" rarely explain what your application was doing when they happened. To attach context for your logs, call context or with_context on any Result. The ErrorContext trait is included in the prelude:

rust
use dust::prelude::*;let license = tokio::fs::read_to_string("license.txt")    .await    .context("the license can't be read")?;let post = Post::find_or_fail(id)    .await    .with_context(|| format!("the post `{id}` can't be loaded"))?;

The context becomes the outer message and the original error becomes its cause, so your logs read the post `42` can't be loaded: no such table: posts. The error keeps its original type, caller location, and status code, so a 404 with context is still a 404 and JSON logs still report the underlying error type rather than anyhow::Error.

Context is meant for developers, not end users. dust-framework logs and reports it and displays it on the debug page, but omits it from normal responses so you can safely include IDs or tenant names. A 404 with context still responds with "Not Found". To customize the message users see, customize your error pages.

HTTP errors

Sometimes a handler needs to stop and return an HTTP status directly, such as 404 Not Found or 403 Forbidden. The abort! macro returns from the handler immediately using the status code and optional message you provide. For example, if your User model has a banned field, this handler hides profiles of banned users:

You have Use
A status to return dust::abort!(403)
A status and a public message dust::abort!(409, "The name is taken.")
A status and response headers dust::abort(429).with_header("retry-after", "60")
An Option that must be present .or_abort(404)?
A condition that must hold dust::abort_if(..) or dust::abort_unless(..)
rust
use dust::prelude::*;use crate::models::User;pub async fn show(Params(id): Params<i64>) -> dust::Result<Json<User>> {    let user = User::find_or_fail(id).await?;    if user.banned {        dust::abort!(404);    }    Ok(Json(user))}

The status may be a number or a StatusCode, and the optional message accepts format! arguments:

rust
dust::abort!(StatusCode::FORBIDDEN);dust::abort!(409, "The name `{}` is taken.", user.name);

To turn an Option::None into an HTTP error, call or_abort. Its OrAbort trait is included in the prelude:

rust
let user = User::find(id).await?.or_abort(404)?;

Aborting when a condition holds

You may abort conditionally with abort_if (which fails when the condition is true) and abort_unless (which fails when it's false). For example, if your Post model has a user_id field, this handler allows only the post's author to edit it:

rust
use dust::prelude::*;use dust::view::View;use crate::models::{Post, User};pub async fn edit(    user: Authenticated<User>,    Params(id): Params<i64>,) -> dust::Result<View> {    let post = Post::find_or_fail(id).await?;    dust::abort_if(post.user_id != user.id, 403)?;    Ok(view("posts.edit", data! { post }))}

For reusable permission checks across multiple handlers, a policy is usually clearer than repeating conditions in each handler.

Headers

Any error may carry response headers, such as Retry-After on a 429 Too Many Requests response, and dust-framework includes them whether the error renders as JSON or HTML. The abort and abort_with functions build an Error without returning it immediately, so you may attach headers before returning:

rust
return Err(dust::abort(429).with_header("retry-after", "60"));

Invalid input

Validation rules catch most invalid input before your handler runs. When your handler discovers a problem that rules can't express, such as an email address that has already been invited, return an InvalidInput error with a message for each invalid field using the invalid! macro:

rust
use dust::validation::invalid;invalid!(email => "That email is already invited.");

dust-framework treats InvalidInput as a failed validation. For browser form submissions, dust-framework redirects back to the form with the errors and old input. For API requests, dust-framework responds with 422 Unprocessable Content and a JSON payload listing each field's errors:

json
{    "message": "That email is already invited.",    "errors": {        "email": ["That email is already invited."]    }}

To learn more about defining validation rules and returning validation errors, check out the validation guide.

Failures and expected outcomes

dust-framework handles errors differently depending on their HTTP status code:

  • Failures have a 5xx server status, such as 500 or 503. dust-framework reports them by logging the error and passing it to your reporters, and hides their internal message from users unless you raised the error with abort_with.
  • Expected outcomes have any non-5xx status, usually a 4xx client status such as 404, 403, or 422. dust-framework doesn't report them. JSON responses include the error's message, while HTML error pages display its status.

Reporting and carrying on

Sometimes a failure shouldn't break the entire request. For example, a product page can still render without its recommendations, even though you want to know that the recommendation service is down. Call dust::report to log and report the error while your handler continues.

This handler fetches recommendations with the HTTP client. If the request fails, it reports the error and renders the page with an empty list:

rust
use dust::http::client;use dust::prelude::*;use dust::view::View;use crate::models::Product;pub async fn show(Params(id): Params<i64>) -> dust::Result<View> {    let product = Product::find_or_fail(id).await?;    let recommendations = client::get(format!(        "https://recommendations.example.com/products/{id}",    ))        .ensure_successful()        .await        .and_then(|response| response.json::<Vec<serde_json::Value>>())        .unwrap_or_else(|error| {            dust::report(error);            Vec::new()        });    Ok(view("products.show", data! { product, recommendations }))}

dust::report logs the error with the request's context and passes it to your reporters. It skips expected outcomes, so dust::report(dust::abort(404)) does nothing.

Panics

If a handler panics, dust-framework catches the panic, logs the file and line where it happened, and renders a 500 response while your application continues serving other requests. Even so, return Result errors for failures you anticipate and reserve panics for bugs.

Error pages

Requests that want JSON, along with every request to a route in the api group, receive errors as JSON, such as { "message": "Not Found" }. All other requests receive an HTML error page.

In JSON responses, "message" comes from the error that set the status code, whether passed to abort! or abort_with, or defined with #[error("...")] on an error type that derives Status:

rust
dust::abort!(404, "That post doesn't exist.");

For example, returning BookingConflict (409) produces "This time slot is already booked", even if you attached internal context. A missing model produces ModelNotFound's message naming the model and key, while server failures return "Server Error" unless debug mode is enabled or you used abort_with.

HTML error pages display the status code and reason phrase, such as "404 Not Found" or "419 Page Expired", whether debug mode is on or off. A 403 page displays the error's message instead so a policy's denial can explain why access was refused. When debug mode is on, server failures render the debug page instead.

To customize your error pages, create a view named after the status code, such as resources/views/errors/404.html. You may also create fallback views at errors/4xx.html and errors/5xx.html for any status without a dedicated view. Each view receives status and message:

html
{% extends "layouts.app" %}{% block content %}    <h1>{{ status }}</h1>    <p>{{ message }}</p>{% endblock %}

dust-framework looks for the exact status first, then the range's fallback, then its built-in page:

Request View it tries
GET /missing (404) errors/404.html, then errors/4xx.html
A failed query (500) errors/500.html, then errors/5xx.html
A validation error (422) errors/422.html, then errors/4xx.html

A 403 from a policy carries the denial's message in message, while the other pages usually show a short reason phrase. Error views are ordinary views, so they may extend your layout and use the same partials as the rest of your site.

To learn more about setting titles and other metadata on error pages, check out the head metadata guide's section on error pages.

Customizing the error handler

To customize how your application reports and renders errors, call with_errors in src/app.rs. Its closure receives the Errors builder and your application's configuration, so you may conditionally register reporters when an error tracker's key is configured:

rust
use dust::prelude::*;Application::configure()    .with_errors(|errors, config| {        // ...    })

Reporting errors

dust-framework logs every server failure automatically. To also send failures of a specific type to an external service, register a reporter for that type inside with_errors:

rust
errors.report(|error: &PaymentError| {    // Send the error to your error tracker...});

To report every failure regardless of its type, use report_all. Its closure receives dust::Error, which you may inspect:

rust
errors.report_all(|error| {    // Send every failure to your error tracker...});

If your error tracker integrates with tracing, such as Sentry, you don't need a custom reporter. dust-framework logs every failure at the error level, so adding the tracker's tracing layer captures them automatically.

Ignoring errors by type

To keep expected failures out of your logs and reporters, ignore their type with dont_report. For example, an application that already retries failed calls to a partner API might ignore HTTP client errors:

rust
use dust::http::client;errors.dont_report::<client::Error>();

Ignored errors still render responses as usual.

Rendering errors

To render a specific error type your own way, register a renderer with render. Your closure receives the error, the request, and the error's status code, and returns Option<Response>. Returning None falls back to dust-framework's default rendering.

dust-framework sends whatever response your renderer returns, so include the status code or the response will be 200 OK. Check request.wants_json() when your renderer serves both API clients and browsers. For example, this renderer returns the decline reason as JSON for API clients and renders a view for browsers:

rust
use dust::prelude::*;use serde_json::json;errors.render(|error: &PaymentError, request, status| {    let PaymentError::Declined { reason } = error else {        return None;    };    if request.wants_json() {        let body = json!({            "message": error.to_string(),            "reason": reason,        });        return Some((status, Json(body)).into_response());    }    let page = view("errors.card-declined", data! { reason });    Some((status, page).into_response())});

Adjusting every error response

To modify every rendered error response, register a callback with respond. It receives the rendered Response, the error, and the request, and returns the response to send. For example, this responder prevents browsers and proxies from caching error pages:

rust
errors.respond(|response, _error, _request| {    response.with_header("cache-control", "no-store")});

Keeping input out of old input

When an invalid form redirects back, dust-framework flashes the submitted fields to the session as old input. dust-framework never flashes password, password_confirmation, or current_password. To exclude additional sensitive fields, list them with dont_flash, using "dot" notation for nested fields:

rust
errors.dont_flash(["ssn", "card.number", "card.cvc"]);

Errors from packages

Packages configure their own errors through app.errors() in their service provider's register method, using the same Errors builder as with_errors. Your application's with_errors runs after every service provider, so your status mappings override a package's for the same error type, and your renderers run first (returning None falls back to the package's renderer). To learn more about registering errors in a package, check out the package development guide's section on errors.

Inspecting errors

Inside reporters, responders, and tests, you may inspect a dust::Error with these methods:

Method Returns
status() Its status code, such as StatusCode::PAYMENT_REQUIRED.
is::<PaymentError>() Whether it's a PaymentError.
downcast_ref::<PaymentError>() The underlying PaymentError, if it is one.
chain() Its context messages, followed by the error and its causes.
location() Where it was created, such as src/http/handlers/orders.rs:42:31.

Testing errors

In HTTP tests, each response retains the error it was rendered from, so you may assert directly on error types rather than matching HTML text. Use assert_error to check the rendered error's type, assert_reported and assert_not_reported to check whether a specific error type was reported (including via dust::report), and assert_nothing_reported to verify that no failures were reported at all:

rust
use dust::http::client;use dust::model::create;use dust::testing::prelude::*;use crate::models::Product;#[dust::test]async fn a_declined_card_is_a_payment_error(app: Application) {    app.post("/checkout")        .await        .assert_payment_required()        .assert_error::<PaymentError>()        .assert_nothing_reported();}#[dust::test]async fn products_show_without_recommendations(app: Application) -> dust::Result<()> {    let product = create!(Product { name: "Desk lamp" }).await?;    let _http = client::fake()        .with("recommendations.example.com/*", client::failed_connection());    app.get(format!("/products/{}", product.id))        .await        .assert_ok()        .assert_reported::<client::Error>();    Ok(())}