Generic error handler.
(res: &ServiceResponse<B>, error: &str)
| 83 | |
| 84 | // Generic error handler. |
| 85 | fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> HttpResponse<BoxBody> { |
| 86 | let request = res.request(); |
| 87 | |
| 88 | // Provide a fallback to a simple plain text response in case an error occurs during the |
| 89 | // rendering of the error page. |
| 90 | let fallback = |err: &str| { |
| 91 | HttpResponse::build(res.status()) |
| 92 | .content_type(ContentType::plaintext()) |
| 93 | .body(err.to_string()) |
| 94 | }; |
| 95 | |
| 96 | let hb = request |
| 97 | .app_data::<web::Data<Handlebars>>() |
| 98 | .map(|t| t.get_ref()); |
| 99 | match hb { |
| 100 | Some(hb) => { |
| 101 | let data = json!({ |
| 102 | "error": error, |
| 103 | "status_code": res.status().as_str() |
| 104 | }); |
| 105 | let body = hb.render("error", &data); |
| 106 | |
| 107 | match body { |
| 108 | Ok(body) => HttpResponse::build(res.status()) |
| 109 | .content_type(ContentType::html()) |
| 110 | .body(body), |
| 111 | Err(_) => fallback(error), |
| 112 | } |
| 113 | } |
| 114 | None => fallback(error), |
| 115 | } |
| 116 | } |