next_rust_server/
error.rs1use std::collections::BTreeMap;
4use std::fmt;
5
6use http::StatusCode;
7
8type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
9
10pub struct Error {
16 kind: ErrorKind,
17}
18
19pub enum ErrorKind {
20 NotFound,
22 Redirect { location: String, status: StatusCode },
24 Http { status: StatusCode, message: String },
26 Validation(BTreeMap<String, String>),
28 DynamicUsage(&'static str),
30 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 pub fn msg(message: impl Into<String>) -> Self {
49 Error { kind: ErrorKind::Internal(message.into().into()) }
50 }
51
52 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 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 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 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
147pub type Result<T, E = Error> = std::result::Result<T, E>;
149
150pub fn not_found() -> Error {
152 Error { kind: ErrorKind::NotFound }
153}
154
155pub fn redirect(location: impl Into<String>) -> Error {
157 Error { kind: ErrorKind::Redirect { location: location.into(), status: StatusCode::TEMPORARY_REDIRECT } }
158}
159
160pub fn permanent_redirect(location: impl Into<String>) -> Error {
162 Error { kind: ErrorKind::Redirect { location: location.into(), status: StatusCode::PERMANENT_REDIRECT } }
163}
164
165pub 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
176pub 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);