| 1 | //! Error pages. |
| 2 | |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | use askama::Template; |
| 6 | use axum::extract::State; |
| 7 | use axum::http::{HeaderValue, StatusCode, header}; |
| 8 | use axum::response::Response; |
| 9 | |
| 10 | use super::{Layout, render}; |
| 11 | use crate::state::AppState; |
| 12 | |
| 13 | #[derive(Template)] |
| 14 | #[template(path = "error.html")] |
| 15 | pub struct ErrorPage { |
| 16 | pub layout: Layout, |
| 17 | pub code: u16, |
| 18 | pub message: String, |
| 19 | } |
| 20 | |
| 21 | pub fn page(state: &AppState, status: StatusCode, message: impl Into<String>) -> Response { |
| 22 | let config = state.config.load(); |
| 23 | let code = status.as_u16(); |
| 24 | let page = ErrorPage { |
| 25 | layout: Layout::new(state, &config, Some(&code.to_string())), |
| 26 | code, |
| 27 | message: message.into(), |
| 28 | }; |
| 29 | let mut res = render(status, &page); |
| 30 | if status.is_server_error() { |
| 31 | res.headers_mut() |
| 32 | .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store")); |
| 33 | } |
| 34 | res |
| 35 | } |
| 36 | |
| 37 | /// 503 for load shedding; clients may retry shortly. |
| 38 | pub fn busy(state: &AppState) -> Response { |
| 39 | let mut res = page(state, StatusCode::SERVICE_UNAVAILABLE, "SERVER BUSY"); |
| 40 | res.headers_mut() |
| 41 | .insert(header::RETRY_AFTER, HeaderValue::from_static("10")); |
| 42 | res |
| 43 | } |
| 44 | |
| 45 | pub fn method_not_allowed(state: &AppState) -> Response { |
| 46 | let mut res = page(state, StatusCode::METHOD_NOT_ALLOWED, "METHOD NOT ALLOWED"); |
| 47 | res.headers_mut() |
| 48 | .insert(header::ALLOW, HeaderValue::from_static("GET, HEAD")); |
| 49 | res |
| 50 | } |
| 51 | |
| 52 | pub async fn not_found(State(state): State<Arc<AppState>>) -> Response { |
| 53 | page(&state, StatusCode::NOT_FOUND, "PAGE NOT FOUND") |
| 54 | } |