Generic error handler.
(res: &ServiceResponse<B>, error: &str)
| 67 | |
| 68 | // Generic error handler. |
| 69 | fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> HttpResponse { |
| 70 | let request = res.request(); |
| 71 | |
| 72 | // Provide a fallback to a simple plain text response in case an error occurs during the |
| 73 | // rendering of the error page. |
| 74 | let fallback = |err: &str| { |
| 75 | HttpResponse::build(res.status()) |
| 76 | .content_type(ContentType::plaintext()) |
| 77 | .body(err.to_string()) |
| 78 | }; |
| 79 | |
| 80 | let tera = request.app_data::<web::Data<Tera>>().map(|t| t.get_ref()); |
| 81 | match tera { |
| 82 | Some(tera) => { |
| 83 | let mut context = tera::Context::new(); |
| 84 | context.insert("error", error); |
| 85 | context.insert("status_code", res.status().as_str()); |
| 86 | let body = tera.render("error.html", &context); |
| 87 | |
| 88 | match body { |
| 89 | Ok(body) => HttpResponse::build(res.status()) |
| 90 | .content_type(ContentType::html()) |
| 91 | .body(body), |
| 92 | Err(_) => fallback(error), |
| 93 | } |
| 94 | } |
| 95 | None => fallback(error), |
| 96 | } |
| 97 | } |