Skip to main content

next_rust_server/
error.rs

1//! The error type used by pages, layouts, loaders, API routes and actions.
2
3use std::collections::BTreeMap;
4use std::fmt;
5
6use http::StatusCode;
7
8type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
9
10/// Framework error.
11///
12/// Any `std::error::Error` converts into it with `?`. Control-flow variants
13/// ([`not_found`], [`redirect`]) are created with helper functions and
14/// returned like errors: `return Err(redirect("/login"))`.
15pub struct Error {
16    kind: ErrorKind,
17}
18
19pub enum ErrorKind {
20    /// Render the nearest `not-found.rs` (404).
21    NotFound,
22    /// Redirect to `location`.
23    Redirect { location: String, status: StatusCode },
24    /// An HTTP error with a public message.
25    Http { status: StatusCode, message: String },
26    /// Field validation failed (form handling, server actions).
27    Validation(BTreeMap<String, String>),
28    /// A request-bound API was used while rendering a static page.
29    DynamicUsage(&'static str),
30    /// Unexpected failure. The message is only shown in development.
31    Internal(BoxError),
32}
33
34impl Error {
35    pub fn kind(&self) -> &ErrorKind {
36        &self.kind
37    }
38
39    pub fn into_kind(self) -> ErrorKind {
40        self.kind
41    }
42
43    pub fn new(kind: ErrorKind) -> Self {
44        Error { kind }
45    }
46
47    /// Internal error from a message.
48    pub fn msg(message: impl Into<String>) -> Self {
49        Error { kind: ErrorKind::Internal(message.into().into()) }
50    }
51
52    /// HTTP error with a message that is safe to show to users.
53    pub fn http(status: u16, message: impl Into<String>) -> Self {
54        Error {
55            kind: ErrorKind::Http {
56                status: StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
57                message: message.into(),
58            },
59        }
60    }
61
62    /// Validation errors keyed by field name.
63    pub fn validation<I, K, V>(fields: I) -> Self
64    where
65        I: IntoIterator<Item = (K, V)>,
66        K: Into<String>,
67        V: Into<String>,
68    {
69        Error { kind: ErrorKind::Validation(fields.into_iter().map(|(k, v)| (k.into(), v.into())).collect()) }
70    }
71
72    pub fn status(&self) -> StatusCode {
73        match &self.kind {
74            ErrorKind::NotFound => StatusCode::NOT_FOUND,
75            ErrorKind::Redirect { status, .. } => *status,
76            ErrorKind::Http { status, .. } => *status,
77            ErrorKind::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
78            ErrorKind::DynamicUsage(_) | ErrorKind::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
79        }
80    }
81
82    pub fn is_not_found(&self) -> bool {
83        matches!(self.kind, ErrorKind::NotFound)
84    }
85
86    pub fn is_redirect(&self) -> bool {
87        matches!(self.kind, ErrorKind::Redirect { .. })
88    }
89
90    /// Message safe for end users in production.
91    pub fn public_message(&self) -> String {
92        match &self.kind {
93            ErrorKind::NotFound => "Not Found".into(),
94            ErrorKind::Redirect { location, .. } => format!("Redirecting to {location}"),
95            ErrorKind::Http { message, .. } => message.clone(),
96            ErrorKind::Validation(_) => "Validation failed".into(),
97            ErrorKind::DynamicUsage(_) | ErrorKind::Internal(_) => "Internal Server Error".into(),
98        }
99    }
100
101    /// Full message including internal details (development only).
102    pub fn detailed_message(&self) -> String {
103        match &self.kind {
104            ErrorKind::Internal(e) => {
105                let mut s = e.to_string();
106                let mut source = e.source();
107                while let Some(inner) = source {
108                    s.push_str(&format!("\n  caused by: {inner}"));
109                    source = inner.source();
110                }
111                s
112            }
113            ErrorKind::DynamicUsage(what) => format!(
114                "`{what}` reads request data, but this page is rendered statically.\n\
115                 Mark the route dynamic with `pub const RENDERING: Rendering = Rendering::Dynamic;`\n\
116                 or remove the request-bound argument."
117            ),
118            ErrorKind::Validation(fields) => {
119                fields.iter().map(|(k, v)| format!("{k}: {v}")).collect::<Vec<_>>().join("\n")
120            }
121            _ => self.public_message(),
122        }
123    }
124}
125
126impl fmt::Debug for Error {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        write!(f, "Error({}: {})", self.status(), self.detailed_message())
129    }
130}
131
132impl fmt::Display for Error {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        f.write_str(&self.detailed_message())
135    }
136}
137
138impl<E> From<E> for Error
139where
140    E: std::error::Error + Send + Sync + 'static,
141{
142    fn from(e: E) -> Self {
143        Error { kind: ErrorKind::Internal(Box::new(e)) }
144    }
145}
146
147/// `Result` alias with [`Error`] as the default error type.
148pub type Result<T, E = Error> = std::result::Result<T, E>;
149
150/// Render the nearest `not-found.rs` with status 404.
151pub fn not_found() -> Error {
152    Error { kind: ErrorKind::NotFound }
153}
154
155/// Temporary redirect (307, method preserved).
156pub fn redirect(location: impl Into<String>) -> Error {
157    Error { kind: ErrorKind::Redirect { location: location.into(), status: StatusCode::TEMPORARY_REDIRECT } }
158}
159
160/// Permanent redirect (308, method preserved).
161pub fn permanent_redirect(location: impl Into<String>) -> Error {
162    Error { kind: ErrorKind::Redirect { location: location.into(), status: StatusCode::PERMANENT_REDIRECT } }
163}
164
165/// Convert `None` into a 404.
166pub trait OrNotFound<T> {
167    fn or_not_found(self) -> Result<T>;
168}
169
170impl<T> OrNotFound<T> for Option<T> {
171    fn or_not_found(self) -> Result<T> {
172        self.ok_or_else(not_found)
173    }
174}
175
176/// Accept both `T` and `Result<T, E>` from user functions (generated code).
177pub trait IntoResult<T> {
178    fn into_result(self) -> Result<T>;
179}
180
181impl<T, E: Into<Error>> IntoResult<T> for std::result::Result<T, E> {
182    fn into_result(self) -> Result<T> {
183        self.map_err(Into::into)
184    }
185}
186
187macro_rules! plain_into_result {
188    ($($t:ty),*) => {$(
189        impl IntoResult<$t> for $t {
190            fn into_result(self) -> Result<$t> {
191                Ok(self)
192            }
193        }
194    )*};
195}
196
197plain_into_result!(next_rust_view::Metadata, Vec<next_rust_router::Params>, crate::seo::Sitemap, crate::seo::Robots);