Generic error handler.
(res: &ServiceResponse<B>, error: &str)
| 72 | |
| 73 | // Generic error handler. |
| 74 | fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> HttpResponse { |
| 75 | let request = res.request(); |
| 76 | |
| 77 | // Provide a fallback to a simple plain text response in case an error occurs during the |
| 78 | // rendering of the error page. |
| 79 | let fallback = |err: &str| { |
| 80 | HttpResponse::build(res.status()) |
| 81 | .content_type(ContentType::plaintext()) |
| 82 | .body(err.to_string()) |
| 83 | }; |
| 84 | |
| 85 | let tt = request |
| 86 | .app_data::<web::Data<TinyTemplate<'_>>>() |
| 87 | .map(|t| t.get_ref()); |
| 88 | match tt { |
| 89 | Some(tt) => { |
| 90 | let mut context = std::collections::HashMap::new(); |
| 91 | context.insert("error", error.to_owned()); |
| 92 | context.insert("status_code", res.status().as_str().to_owned()); |
| 93 | let body = tt.render("error.html", &context); |
| 94 | |
| 95 | match body { |
| 96 | Ok(body) => HttpResponse::build(res.status()) |
| 97 | .content_type(ContentType::html()) |
| 98 | .body(body), |
| 99 | Err(_) => fallback(error), |
| 100 | } |
| 101 | } |
| 102 | None => fallback(error), |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | static ERROR: &str = include_str!("../templates/error.html"); |
| 107 | static INDEX: &str = include_str!("../templates/index.html"); |