Skip to main content

egui_kit/
error.rs

1//! What navigations fail with: [`Rejection`], made of a [`RouteError`] or a [`Redirect`].
2
3use core::convert::Infallible;
4use std::fmt;
5
6/// An error that aborts a navigation and renders the nearest error page.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub struct RouteError {
9    pub status: u16,
10    pub message: String,
11}
12
13impl RouteError {
14    pub fn new(status: u16, message: impl Into<String>) -> Self {
15        Self {
16            status,
17            message: message.into(),
18        }
19    }
20
21    pub fn not_found(message: impl Into<String>) -> Self {
22        Self::new(404, message)
23    }
24
25    pub fn bad_request(message: impl Into<String>) -> Self {
26        Self::new(400, message)
27    }
28
29    pub fn internal(message: impl Into<String>) -> Self {
30        Self::new(500, message)
31    }
32}
33
34impl fmt::Display for RouteError {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "{}: {}", self.status, self.message)
37    }
38}
39
40impl core::error::Error for RouteError {}
41
42/// Aborts a navigation and navigates to another url instead.
43///
44/// The history gets the url redirected to, not the one that redirected: a navigation that adds
45/// an entry ([`Nav::goto`](crate::extract::Nav::goto), a link) adds one for it, and any other (a
46/// replace, back/forward, the first page, a reload) replaces the current entry with it. More
47/// than 20 redirects in a row fail with a 500.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct Redirect {
50    pub to: String,
51}
52
53impl Redirect {
54    pub fn to(to: impl Into<String>) -> Self {
55        Self { to: to.into() }
56    }
57}
58
59/// Everything a hook, a `load` handler or an extractor can abort a navigation with.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum Rejection {
62    Error(RouteError),
63    Redirect(Redirect),
64}
65
66impl From<RouteError> for Rejection {
67    fn from(err: RouteError) -> Self {
68        Self::Error(err)
69    }
70}
71
72impl From<Redirect> for Rejection {
73    fn from(redirect: Redirect) -> Self {
74        Self::Redirect(redirect)
75    }
76}
77
78impl From<Infallible> for Rejection {
79    fn from(never: Infallible) -> Self {
80        match never {}
81    }
82}
83
84/// Shorthand for `Rejection::Error(RouteError::new(status, message))`.
85pub fn error(status: u16, message: impl Into<String>) -> Rejection {
86    RouteError::new(status, message).into()
87}
88
89/// Shorthand for `Rejection::Redirect(Redirect::to(to))`. See [`Redirect`] for how it updates
90/// the history.
91pub fn redirect(to: impl Into<String>) -> Rejection {
92    Redirect::to(to).into()
93}