如题,两个例子都要自己实现IntoResponse
第一例子用anyhow, 似乎所有的错误都只能用一个状态码
// Make our own error that wraps `anyhow::Error`.
struct AppError(anyhow::Error);
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
第二个例子自定义错误类型,但是不能明了的看到用了什么状态码,要是thiserror这个库的宏有个status属性并自动实现IntoResponse感觉就不错
// The kinds of errors we can hit in our application.
enum AppError {
// The request body contained invalid JSON
JsonRejection(JsonRejection),
// Some error from a third party library we're using
TimeError(time_library::Error),
}
// Tell axum how `AppError` should be converted into a response.
//
// This is also a convenient place to log errors.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
unimplemented!()
}
}
1
共 1 条评论, 1 页
评论区
写评论供参考: