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