Skip to main content

rust_webx_core/
error.rs

1//! Unified error type for the rust-webx framework.
2
3use thiserror::Error;
4
5/// Framework-wide error type.
6#[derive(Error, Debug)]
7pub enum Error {
8    #[error("HTTP error: {0}")]
9    Http(String),
10
11    #[error("Status {0}: {1}")]
12    Status(u16, String),
13
14    #[error("Unauthorized: {0}")]
15    Unauthorized(String),
16
17    #[error("Forbidden: {0}")]
18    Forbidden(String),
19
20    #[error("DI error: {0}")]
21    Di(String),
22
23    #[error("Routing error: {0}")]
24    Routing(String),
25
26    #[error("Serialization error: {0}")]
27    Serialization(#[from] serde_json::Error),
28
29    #[error("Internal error: {0}")]
30    Internal(String),
31
32    #[error("{0}")]
33    Message(String),
34
35    /// Validation error with user-readable message.
36    #[error("{0}")]
37    Validation(String),
38
39    /// Resource not found.
40    #[error("{0}")]
41    NotFound(String),
42
43    /// Optimistic concurrency or state conflict.
44    #[error("{0}")]
45    Conflict(String),
46
47    /// Request body (or one uploaded file) exceeded the configured limit.
48    #[error("{0}")]
49    PayloadTooLarge(String),
50
51    /// Request content type is not supported by the target endpoint.
52    #[error("{0}")]
53    UnsupportedMediaType(String),
54}
55
56impl Error {
57    /// Map the error to an appropriate HTTP status code.
58    ///
59    /// Used by the built-in exception middleware to produce
60    /// well-formed HTTP error responses.
61    pub fn status_code(&self) -> u16 {
62        match self {
63            Error::Http(_) => 400,
64            Error::Status(code, _) => *code,
65            Error::Unauthorized(_) => 401,
66            Error::Forbidden(_) => 403,
67            Error::Di(_) => 500,
68            Error::Routing(_) => 404,
69            Error::Serialization(_) => 400,
70            Error::Internal(_) => 500,
71            Error::Message(_) => 500,
72            Error::Validation(_) => 400,
73            Error::NotFound(_) => 404,
74            Error::Conflict(_) => 409,
75            Error::PayloadTooLarge(_) => 413,
76            Error::UnsupportedMediaType(_) => 415,
77        }
78    }
79}
80
81/// Shorthand for Result<T, Error>.
82pub type Result<T> = std::result::Result<T, Error>;