本章我们将自定义错误、自定义一个Result
以及让它们作为 handler 的返回值,进行 HTTP 响应。
本章代码在02/错误处理分支。
自定义错误
我们将定义自己的错误类型,在项目内都将使用该自定义错误。同时,我们还会将对该自定义错误实现IntoResponse
,以便在 handler 中作为返回值使用。
首先,在src/main.rs
声明error
模块:
接着声明自定义错误的结构体和相关的枚举:
最后,为这个自定义错误实现IntoResponse
:
/// 实现 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>;
下一章我们将自定义响应。