1use std::fmt;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Debug)]
9pub enum Error {
10 BadRequest(String),
12 Unauthorized(String),
14 Forbidden(String),
16 NotFound(String),
18 Internal(String),
20 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
56impl 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}