`ResponseError` is the Actix Web trait that turns an error returned by a handler into an HTTP response. Actix already implements it for common errors, including `std::io::Error`: if a handler propagates a failed `File::open` with `?`, the client receives an error response rather than a successful handler result. section 5.2
For application-specific responses, define one error type and carry it through the request path:
- Create an error enum in `src/iter4/errors.rs`, with variants such as `DBError`, `ActixError`, and `NotFound`. Use a separate serializable response type for the client-facing `error_message`. section 5.3
- Implement `From` conversions for underlying errors, including database and Actix errors, so handlers and database functions can return the custom type. section 5.3 section 5.7
- Implement `ResponseError`: map database and Actix errors to `500 Internal Server Error`, and missing records to `404 Not Found`. Build a JSON `HttpResponse` using that status and the client-facing message. section 5.3
Listing 5.3 Error handling: part 3
impl error::ResponseError for EzyTutorError {
fn status_code(&self) -> StatusCode { #1
match self {
EzyTutorError::DBError(msg) | EzyTutorError::ActixError(msg) => {
StatusCode::INTERNAL_SERVER_ERROR
}
EzyTutorError::NotFound(msg) => StatusCode::NOT_FOUND,
}
}
fn error_response(&self) -> HttpResponse { #2
HttpResponse::build(self.status_code()).json(MyErrorResponse {
error_message: self.error_response(),
})
}
}
The implementation keeps the two HTTP decisions together: `status_code()` selects the status, while the trait’s `error_response()` builds the JSON body. An inherent helper with the same name supplies the message string. section 5.3
A missing course
A course lookup returns `EzyTutorError::NotFound("Course id not found".into())` when no row exists. The handler returns `Result<HttpResponse, EzyTutorError>` and passes the database result through; Actix uses `ResponseError` to produce the client response. A failure test calls `status_code()` on the returned error and checks for `NOT_FOUND`. section 6.2.2 section 5.3
