Closed crmckenzie closed 5 years ago
you have to implement .render_response()
Thank you for taking the time to review the issue and respond. It's very much appreciated.
I didn't see that ResponseError
had a render_response
method because the docs say there is only one method on the trait:
ResponseError has a single function called error_response() that returns HttpResponse
Here is my solution that works:
impl ResponseError for MyError {
fn error_response(&self) -> HttpResponse {
dbg!("ResponseError.error_response(&self) being called.");
HttpResponse::InternalServerError()
.json(self) // I really wish this was all I had to do.
}
// this makes the respose come back as a json blob.
fn render_response(&self) -> Response {
let resp = self.error_response();
let json = serde_json::to_string(self);
match json {
Ok(json_text) => {
let new_body = Body::from(json_text);
resp.set_body(new_body)
},
Err(_) => {
resp
}
}
}
}
This still seems awkward to me since I already specified in error_response
that I wanted the result serialized to json. If I can figure out how to do it, would you accept a PR that makes it unnecessary to implement render_response
in this scenario?
Pr is always welcomed. Just your idea before
re-open if needed
So I encountered this exact thing today, and it is was confusing to figure out. @fafhrd91 What is the reason for having both render_response()
and error_response()
in the trait? I have implemented it as recommended in MIGRATION.md, but I want to know if there is a benefit to only adding the body in the render_response()
method?
impl ResponseError for Error {
fn error_response(&self) -> HttpResponse {
HttpResponse::InternalServerError().json(self)
}
fn render_response(&self) -> HttpResponse {
self.error_response()
}
}
When attempting to serialize a custom error to json as part of the
ResponseError
implementation, actix-web obliterates the body I provided in favor of thefmt::Display
implementation for the same struct. While I appreciate that actix-web wants to coerce my error response to a body on my behalf, I would expect that if I have provided a body that actix-web would not replace it later.Here is the interesting bit:
Here is the curl command:
Here is the logging output. You can see that fmt::Display is being invoked after the ResponseError transformation.
Here is an entire working example.