Skip to main content

ullun/
error.rs

1//! Error types and Result alias
2
3use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7/// Framework error type that maps to HTTP status codes
8#[derive(Debug)]
9pub enum Error {
10    /// 400 Bad Request
11    BadRequest(String),
12    /// 401 Unauthorized
13    Unauthorized(String),
14    /// 403 Forbidden
15    Forbidden(String),
16    /// 404 Not Found
17    NotFound(String),
18    /// 500 Internal Server Error
19    Internal(String),
20    /// Custom status code + message
21    Custom(u16, String),
22}
23
24impl Error {
25    pub fn status_code(&self) -> u16 {
26        match self {
27            Error::BadRequest(_) => 400,
28            Error::Unauthorized(_) => 401,
29            Error::Forbidden(_) => 403,
30            Error::NotFound(_) => 404,
31            Error::Internal(_) => 500,
32            Error::Custom(code, _) => *code,
33        }
34    }
35
36    pub fn message(&self) -> &str {
37        match self {
38            Error::BadRequest(msg)
39            | Error::Unauthorized(msg)
40            | Error::Forbidden(msg)
41            | Error::NotFound(msg)
42            | Error::Internal(msg)
43            | Error::Custom(_, msg) => msg,
44        }
45    }
46}
47
48impl fmt::Display for Error {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        write!(f, "{}", self.message())
51    }
52}
53
54impl std::error::Error for Error {}
55
56// Convenience constructors
57impl Error {
58    pub fn bad_request(msg: impl Into<String>) -> Self {
59        Error::BadRequest(msg.into())
60    }
61
62    pub fn unauthorized(msg: impl Into<String>) -> Self {
63        Error::Unauthorized(msg.into())
64    }
65
66    pub fn forbidden(msg: impl Into<String>) -> Self {
67        Error::Forbidden(msg.into())
68    }
69
70    pub fn not_found(msg: impl Into<String>) -> Self {
71        Error::NotFound(msg.into())
72    }
73
74    pub fn internal(msg: impl Into<String>) -> Self {
75        Error::Internal(msg.into())
76    }
77
78    pub fn custom(status: u16, msg: impl Into<String>) -> Self {
79        Error::Custom(status, msg.into())
80    }
81}