You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Rust的Tide框架中自定义404页面的实现方法咨询

在Tide框架中实现自定义404页面

无需中间件的简单实现

Tide没有直接提供app.not_found()接口,但可以通过全局兜底路由快速实现自定义404页面,这是最轻量化的方案,无需依赖中间件。

核心逻辑是:在所有业务路由注册完成后,添加一个匹配任意路径的通配路由/*。由于Tide的路由匹配遵循先注册先匹配、具体路由优先于通配路由的规则,只有当所有前置路由都不匹配时,才会进入这个兜底路由。

示例代码:

use tide::{Request, Response, StatusCode};

#[async_std::main]
async fn main() -> tide::Result<()> {
    let mut app = tide::new();

    // 注册你的业务路由
    app.at("/").get(|_| async { Ok("首页内容") });
    app.at("/contact").get(|_| async { Ok("联系我们") });

    // 兜底路由:处理所有未匹配的路径
    app.at("/*").get(|_| async {
        let mut res = Response::new(StatusCode::NotFound);
        // 设置自定义404 HTML内容
        res.set_body(r#"
            <!DOCTYPE html>
            <html>
                <head>
                    <title>404 - 页面不存在</title>
                    <style>body { text-align: center; margin-top: 50px; font-family: sans-serif; }</style>
                </head>
                <body>
                    <h1>😕 404 页面找不到</h1>
                    <p>你访问的路径不存在,请检查地址是否正确。</p>
                </body>
            </html>
        "#);
        res.set_content_type(tide::http::mime::HTML);
        Ok(res)
    });

    app.listen("127.0.0.1:8080").await?;
    Ok(())
}

使用中间件实现(统一处理所有404场景)

如果需要统一处理所有404响应(包括业务逻辑主动返回的404),可以通过中间件拦截响应并替换内容,适合需要全局统一404样式的场景。

步骤1:定义中间件结构体

use tide::{Middleware, Next, Request, Response, StatusCode};

struct CustomNotFoundMiddleware;

步骤2:实现Middleware trait

#[tide::utils::async_trait]
impl<State> Middleware<State> for CustomNotFoundMiddleware {
    async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> tide::Result<Response> {
        // 先让请求执行后续的路由/业务逻辑
        let mut response = next.run(req).await;
        
        // 检查响应状态码是否为404
        if response.status() == StatusCode::NotFound {
            // 替换为自定义404内容
            response.set_body(r#"
                <!DOCTYPE html>
                <html>
                    <head>
                        <title>404 - 资源不存在</title>
                    </head>
                    <body>
                        <h1>404 Not Found</h1>
                        <p>抱歉,你请求的资源无法找到。</p>
                    </body>
                </html>
            "#);
            response.set_content_type(tide::http::mime::HTML);
        }
        
        Ok(response)
    }
}

步骤3:在App中注册中间件

#[async_std::main]
async fn main() -> tide::Result<()> {
    let mut app = tide::new();
    
    // 注册中间件
    app.with(CustomNotFoundMiddleware);

    // 业务路由示例
    app.at("/").get(|_| async { Ok("首页") });
    // 业务逻辑主动返回404的场景也会被中间件处理
    app.at("/api/user/:id").get(|req: Request<()>| async {
        let user_id = req.param("id")?;
        if user_id == "999" {
            // 主动返回404
            Ok(Response::new(StatusCode::NotFound))
        } else {
            Ok(format!("用户ID:{}", user_id))
        }
    });

    app.listen("127.0.0.1:8080").await?;
    Ok(())
}

内容的提问来源于stack exchange,提问作者WhyNotDogie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 06:13:30