本章我们将自定义错误、自定义一个Result以及让它们作为 handler 的返回值,进行 HTTP 响应。

本章代码在02/错误处理分支。

自定义错误

我们将定义自己的错误类型,在项目内都将使用该自定义错误。同时,我们还会将对该自定义错误实现IntoResponse,以便在 handler 中作为返回值使用。

首先,在src/main.rs声明error模块:

接着声明自定义错误的结构体和相关的枚举:

/// 错误的类型
pub enum AppErrorType {
    /// 数据库错误
    DbType,
    /// 未找到
    NotFound,
}

/// 应用错误
pub struct AppError {
    /// 错误信息
    pub message: Option<String>,
    /// 错误原因(上一级的错误)
    pub cause: Option<String>,
    /// 错误类型
    pub error_type: AppErrorType,
}
/// 实现 IntoResponse
impl IntoResponse for AppError {
    type Body = Full<Bytes>;
    type BodyError = Infallible;

    fn into_response(self) -> axum::http::Response<Self::Body> {
        let msg = match self.message {
            Some(msg) => msg,
            None => "".to_string(),
        };
        msg.into_response()
    }
}

定义自己的Result

/// 定义自己的 Result
type Result<T> = std::result::Result<T, error::AppError>;

下一章我们将自定义响应。