Is there anyway to combine anyhow result with http response? #475
Answered
by
leon3s
DennisZhangOiler
asked this question in
Q&A
-
like #[web::get]
async fn index() -> anyhow::Result<impl Responder> |
Beta Was this translation helpful? Give feedback.
Answered by
leon3s
Nov 29, 2024
Replies: 2 comments 1 reply
-
I think the best way is to create your own type and convert the anyhow::Error into your custom type Something like this: #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HttpError {
#[serde(skip)]
pub status: http::StatusCode,
pub msg: String,
}
/// Implement standard error for HttpError
impl std::error::Error for HttpError {}
/// Helper function to convert an HttpError into a ntex::web::HttpResponse
impl web::WebResponseError for HttpError {
fn error_response(&self, _: &web::HttpRequest) -> web::HttpResponse {
web::HttpResponse::build(self.status).json(&self)
}
}
impl From<anyhow::Error> for HttpError {
fn from(err: anyhow::Error) -> Self {
HttpError {
status: http::StatusCode::BAD_REQUEST,
msg: err.to_string(),
}
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
DennisZhangOiler
-
it is possible to override all errors in ntex. I just updated error handling example https://github.com/ntex-rs/examples/blob/master/error_handling/src/main.rs |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the best way is to create your own type and convert the anyhow::Error into your custom type
Something like this: