Skip to content

Is there anyway to combine anyhow result with http response? #475

Answered by leon3s
DennisZhangOiler asked this question in Q&A
Discussion options

You must be logged in to vote

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 {

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@DennisZhangOiler
Comment options

Answer selected by DennisZhangOiler
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants