Errors and logging
A handler fails by returning an error that has a response, and the page shows that response's status and text. What the visitor should not see goes to the server's log through tracing.
Errors
A handler may return Result<_, E> where E implements axum's IntoResponse, so ? works. For an action, IntoActionResponse is implemented for such a Result of patches, and for a page, PageResponse answers with the error in the same way. The error's response is the answer: below, NotesFull answers 409 Conflict with a sentence the visitor reads.
use axum::Router;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use hypersig::html::{button, p};
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
count: i32,
problem: String,
}
struct NotesFull;
impl IntoResponse for NotesFull {
fn into_response(self) -> Response {
(StatusCode::CONFLICT, "You can keep 3 notes.").into_response()
}
}
fn add_one(count: i32) -> Result<i32, NotesFull> {
(count < 3).then_some(count + 1).ok_or(NotesFull)
}
hypersig::routes! {
fn pages(Router<()>);
action ADD: Action<Notes, i32> = post "/notes" => add;
}
async fn add((): (), count: i32) -> Result<Patches<Notes>, NotesFull> {
let count = add_one(count)?;
Ok(Notes::count().patch(count).into())
}
// The page shows the status and the body of a failed call.
let call = ADD.call_with(Notes::count()).error(Notes::problem());
let _add = button().on_click(call).text("Add");
let _problem = p().bind_text(Notes::problem());
let _app: Router = pages(Router::new());An error type without IntoResponse gives the router no answer to send, so routes! does not compile:
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
count: i32,
}
// No `IntoResponse`: the router has no answer to send for it.
struct NotesFull;
// error[E0277]: `Result<Patches<Notes>, NotesFull>` is not a reply of an action on the page whose signals are `Notes`
hypersig::routes! {
fn pages(Router<()>);
action ADD: Action<Notes, i32> = post "/notes" => add;
}
async fn add((): (), count: i32) -> Result<Patches<Notes>, NotesFull> {
let count = (count < 3).then_some(count + 1).ok_or(NotesFull)?;
Ok(Notes::count().patch(count).into())
}What the page shows
An action whose response has a status outside 2xx fails on the page. The runtime writes a message to the signal given to Call::error and the status to the signal given to Call::status. Both are emptied, to "" and 0, when the call is sent. The message depends on the answer:
| Answer | error signal | status signal |
|---|---|---|
Outside 2xx, with a text/plain body, which axum sends for a String or a &str | The body, such as You can keep 3 notes. | The status, such as 409 |
| Outside 2xx, with an empty body or another type, such as a proxy's HTML error page | The status and its reason, such as 502 Bad Gateway | The status |
| 2xx, but redirected, not an answer of the router, or closed before the router finished it | A message of the runtime's own | 0 |
| No answer, such as a dropped connection | The browser's message | 0 |
Each failure is also written to the browser's console. The call of the sample above that fails logs:
hypersig: POST /notes failed with 409: You can keep 3 notes.Busy and failed calls shows these signals on the page and runs a statement on failure.
A handler that panics
A handler of an action, a stream, or an upload that panics before it returns answers 500 Internal Server Error, which the page shows as any failed call, and the default panic hook still prints the message to stderr. A stream's stream is read after the response has begun, so a panic while it is read closes the connection before the answer is complete, and the page sees status 0. A page handler that panics, and a page that panics while it renders, answer 500 Internal Server Error with an empty body.
Refusals in a log
The router answers a request it refuses before the handler runs, listed in Extractors and headers, with a RequestError. A streaming upload's handler receives one when the body goes wrong while it reads, and returns it with ?. Its methods return more than the visitor sees, for a log:
| Item | What it gives |
|---|---|
status() | The status of the response, such as 413 |
Display | One fixed sentence per refusal, which is also the response's body |
source() | What the parser said about a malformed body or arguments, which names the argument type's fields and quotes the visitor's input |
backtrace() | The backtrace captured where the error was created, when RUST_BACKTRACE asks for one |
Logging
The samples on this site write the server's side of an error with eprintln! to stay short. An application logs with tracing: a handler writes an event with tracing::warn! or tracing::error!, and tracing-subscriber writes the events to stderr. TraceLayer from tower-http, put on the router with layer, adds a line for each request with the answer's status and how long it took. Add the three crates to Cargo.toml:
[dependencies]
tower-http = { version = "0.7", features = ["trace"] }
tracing = "0.1"
tracing-subscriber = "0.3"use axum::Router;
use tower_http::trace::{DefaultMakeSpan, DefaultOnResponse, TraceLayer};
use tracing::Level;
hypersig::routes! {
fn pages(Router<()>);
action SAVE: Action<Profile, String> = post "/save" => save;
}
async fn save((): (), name: String) -> Result<Patches<Profile>, (StatusCode, &'static str)> {
if name.is_empty() {
// An event of the application's own, at the level it picks.
tracing::warn!("refused an empty name");
return Err((StatusCode::UNPROCESSABLE_ENTITY, "Write a name."));
}
Ok(Profile::saved().patch(name).into())
}
// Once, at the start of `main`: write each event at INFO or above to stderr.
tracing_subscriber::fmt().with_max_level(Level::INFO).init();
// Each request gets a span with its method and URI, and one line with the
// answer's status and how long it took. Both are DEBUG unless set here.
let trace = TraceLayer::new_for_http()
.make_span_with(DefaultMakeSpan::new().level(Level::INFO))
.on_response(DefaultOnResponse::new().level(Level::INFO));
let _app: Router = pages(Router::new()).layer(trace);What the compiler does not check
The compiler checks that an error has a response, and not what the response says. The text/plain body of a failed action is what the visitor reads, so write a sentence the visitor can act on there, and log the error's own message, which can hold a query or a file path, on the server.
IntoResponse writes, such as a line of plain text, and not with a page of the site. Error pages shows a page for a 404 instead.Next, Uploads sends files with a call.