Catcher
If the status code of Response
is an error, and the Body
in the page is empty, salvo will try to use Catcher
to catch the error and display a friendly error page.
You can return a system default Catcher
through Catcher::default()
, and then add it to Service
.
use salvo::catcher::Catcher;
Service::new(router).catcher(Catcher::default());
The default Catcher
supports sending error pages in XML
, JSON
, HTML
, Text
formats.
You can add a custom error catcher to Catcher
by adding hoop
to the default Catcher
. This error catcher is still a Handler
.
You can add multiple custom error catchers to Catcher
through hoop
. Custom error handlers can be called after handling errors. FlowCtrl::skip_next
method skips the subsequent error program and returns early.
use salvo::catcher::Catcher;
use salvo::prelude::*;
#[handler]
async fn hello() -> &'static str {
"Hello World"
}
#[handler]
async fn error500(res: &mut Response) {
res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let acceptor = TcpListener::new("127.0.0.1:5800").bind().await;
Server::new(acceptor).serve(create_service()).await;
}
fn create_service() -> Service {
let router = Router::new()
.get(hello)
.push(Router::with_path("500").get(error500));
Service::new(router).catcher(Catcher::default().hoop(handle404))
}
#[handler]
async fn handle404(res: &mut Response, ctrl: &mut FlowCtrl) {
if StatusCode::NOT_FOUND == res.status_code.unwrap_or(StatusCode::NOT_FOUND) {
res.render("Custom 404 Error Page");
ctrl.skip_rest();
}
}
[package]
name = "example-custom-error-page"
version = "0.1.0"
edition = "2021"
publish = false
[dependencies]
salvo.workspace = true
tokio = { version = "1", features = ["macros"] }
tracing = "0.1"
tracing-subscriber = "0.3"