日本語

Error pages

What a page handler answers when it cannot build its page, and the one page routes! shows for every request that reaches no page.

What a page handler returns

A page handler returns anything that converts into a PageResponse. A handler that only ever renders returns Page<S> or Option<Page<S>>. One that sometimes answers otherwise returns PageResponse and converts its usual page with .into().

The handler returnsThe response
Page<S>200 OK with the page
Option<Page<S>>The page, or a 404 Not Found for None
PageResponse::with_status(status, page)The page with the status status
PageResponse::not_found()A 404 Not Found
PageResponse::redirect(url)A 303 See Other to url
(parts, response), with parts: IntoResponsePartsThe response with the headers of parts added, such as a Set-Cookie
Result<R, E>, with E: IntoResponseR's response, or the error's, so the handler can use ?

A page goes out with Cache-Control: private, no-cache, because it carries the visitor's signals. A Cache-Control in parts replaces it.

An error page of your own

A page handler that cannot build its page, such as one whose database does not answer, returns an error page of its own with PageResponse::with_status(status: StatusCode, page: Page<S>). The browser shows the page, and the status tells a crawler or a monitor that the request failed. One function that builds the error page lets every handler answer with it.

use axum::http::StatusCode;
use hypersig::html::{h1, p};
use hypersig::{Page, PageResponse, Route};

#[derive(Signals, Serialize, Deserialize)]
struct Order {
    total: i64,
}

#[derive(Signals, Serialize, Deserialize)]
struct Failure {}

hypersig::routes! {
    fn pages(Router<()>);
    const ORDER: Route<i32> = "/orders/{id}" => order;
}

// One error page that every handler can answer with.
fn error_page(status: StatusCode, message: &str) -> PageResponse {
    let page = Page::new("Something went wrong", Failure {})
        .child(h1().text("Something went wrong"))
        .child(p().text(message));
    PageResponse::with_status(status, page)
}

async fn order((): (), id: i32) -> PageResponse {
    let Ok(total) = load_total(id) else {
        return error_page(StatusCode::SERVICE_UNAVAILABLE, "Orders are unavailable. Try again later.");
    };
    Page::new("Order", Order { total }).child(p().bind_text(Order::total().to_text())).into()
}

Pages for missing paths

fn pages(Router<State>) else missing; on the first line of routes! names a handler for each page request that reaches no page:

  • A path no route matches, which gets a 404.
  • A path whose segments do not parse into its route's parameters, which gets a 404.
  • A handler that answers None or PageResponse::not_found(), which gets a 404.
  • A query string that does not deserialize into its route's search parameters, which gets a 400.

The handler receives an Unserved where a page's handler receives its parameters, and may take an extractor as a page's handler does. Its page is sent with the status the Unserved names, unless it comes from PageResponse::with_status. A call to an action, a stream, or an upload at a path no route matches still gets a 404 with an empty body, because a page is no answer to a call.

The handler takes an Unserved, so one written for a page fails to compile:

use hypersig::{Page, Route, Signals};

#[derive(Signals, Serialize, Deserialize)]
struct Shop {}

hypersig::routes! {
    // error[E0277]: `fn((), ()) -> impl Future<Output = Page<Shop>> {missing}`
    // cannot serve this page or action
    fn pages(Router<()>) else missing;
    const HOME: Route = "/" => home;
}

// The handler after `else` takes an `Unserved`, not `()`.
async fn missing((): (), (): ()) -> Page<Shop> {
    Page::new("Not found", Shop {})
}

Reading the request that reached no page

  • Unserved::status(&self) -> StatusCode is the status the page goes out with: 404, or 400 for a query string.
  • Unserved::within(&self, route: Route<P, Q>) -> Option<P> reads the parameters of route from the start of the path. A literal segment must be equal, and a {name} segment takes the request's segment at its place, percent-decoded. A site under /{lang} shows the page in the language of the path this way.
  • Its Display is one fixed sentence per reason, naming the path, which the page can show the visitor, such as "no page is served at /en/oders/3".
  • For a query string, its Error::source is the reader's message, which quotes the query and names the types of the search parameters. It belongs in a log.
use hypersig::html::{a, h1, p};
use hypersig::{Page, PathSegment, Route, Signals, Unserved};

#[derive(Signals, Serialize, Deserialize)]
struct Shop {}

hypersig::routes! {
    fn pages(Router<()>) else missing;
    const HOME: Route<PathSegment> = "/{lang}" => home;
    const ORDER: Route<(PathSegment, u32)> = "/{lang}/orders/{id}" in HOME => order;
}

// `None` sends the visitor the page of `missing`, with a 404.
async fn order((): (), (_lang, id): (PathSegment, u32)) -> Option<Page<Shop>> {
    (id < 100).then(|| Page::new(format!("Order {id}"), Shop {}))
}

// Every page request that reaches no page arrives here: an unknown path,
// a segment that does not parse, a `None`, and a bad query string.
async fn missing((): (), unserved: Unserved) -> Page<Shop> {
    let lang = unserved.within(HOME).unwrap_or(PathSegment::new("en"));
    let (title, back) = if lang.as_str() == "ja" {
        ("ページが見つかりません", "トップへ戻る")
    } else {
        ("Page not found", "Back to the shop")
    };
    Page::new(title, Shop {})
        .child(h1().text(title))
        // The `Display` names the path, for example
        // "no page is served at `/en/oders/3`".
        .child(p().text(unserved.to_string()))
        .child(p().child(a().href(HOME.link_with(lang)).text(back)))
}

What stays unchecked

  • Without else, a 404 has an empty body, and a 400 for a query string has a one-line text body.
  • The function routes! writes registers the else handler as the router's fallback. A later Router::fallback replaces it for paths no route matches, and merging the router with another that has a fallback panics, as axum does for any two fallbacks.
  • An else handler that answers None has no page to fall back on, and the request gets a 404 with an empty body.
  • PageResponse::with_status takes any status, so nothing checks that an error page goes out with an error status.

Next