Catcher

如果 Response 的状态码是错误, 而页面里面的 Body 是空, 这时 salvo 会试图使用 Catcher 捕获这个错误, 显示一个友好的错误页面.

可以通过 Catcher::default() 返回一个系统默认的 Catcher, 然后将它添加到 Service 上.

use salvo::catcher::Catcher;

Service::new(router).catcher(Catcher::default());

默认的 Catcher 支持以 XML, JSON, HTML, Text 格式发送错误页面.

可以通过给这个默认的 Catcher 添加 hoop 的方式, 把自定义的错误捕获程序添加到Catcher上. 这个错误捕获的程序依然是 Handler.

你可以通过 hoopCatcher 添加多个自定义的错误捕获程序. 自定义的错误处理程序可以在处理错误后调用 FlowCtrl::skip_next 方法跳过后续错误程序,提前返回.

main.rs
Cargo.toml
custom-error-page/src/main.rs
use salvo::catcher::Catcher;
use salvo::prelude::*;

// Handler that returns a simple "Hello World" response
#[handler]
async fn hello() -> &'static str {
    "Hello World"
}

// Handler that deliberately returns a 500 Internal Server Error
#[handler]
async fn error500(res: &mut Response) {
    res.status_code(StatusCode::INTERNAL_SERVER_ERROR);
}

#[tokio::main]
async fn main() {
    // Initialize logging system
    tracing_subscriber::fmt().init();

    // Create and start server with custom error handling
    let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
    Server::new(acceptor).serve(create_service()).await;
}

// Create service with custom error handling
fn create_service() -> Service {
    // Set up router with two endpoints:
    // - / : Returns "Hello World"
    // - /500 : Triggers a 500 error
    let router = Router::new()
        .get(hello)
        .push(Router::with_path("500").get(error500));

    // Add custom error catcher for 404 Not Found errors
    Service::new(router).catcher(Catcher::default().hoop(handle404))
}

// Custom handler for 404 Not Found errors
#[handler]
async fn handle404(&self, _req: &Request, _depot: &Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
    // Check if the error is a 404 Not Found
    if StatusCode::NOT_FOUND == res.status_code.unwrap_or(StatusCode::NOT_FOUND) {
        // Return custom error page
        res.render("Custom 404 Error Page");
        // Skip remaining error handlers
        ctrl.skip_rest();
    }
}