Skip to main content

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    /// A fully-formed problem response (validation, binding failure).
56    ///
57    /// Carried as-is instead of being flattened into a message so the host can
58    /// write the status and the extension members (`errors`) verbatim.
59    #[error("request problem details")]
60    Problem(Box<crate::problem::ProblemDetails>),
61}
62
63impl Error {
64    /// Map the error to an appropriate HTTP status code.
65    ///
66    /// Used by the built-in exception middleware to produce
67    /// well-formed HTTP error responses.
68    pub fn status_code(&self) -> u16 {
69        match self {
70            Error::Http(_) => 400,
71            Error::Status(code, _) => *code,
72            Error::Unauthorized(_) => 401,
73            Error::Forbidden(_) => 403,
74            Error::Di(_) => 500,
75            Error::Routing(_) => 404,
76            Error::Serialization(_) => 400,
77            Error::Internal(_) => 500,
78            Error::Message(_) => 500,
79            Error::Validation(_) => 400,
80            Error::NotFound(_) => 404,
81            Error::Conflict(_) => 409,
82            Error::PayloadTooLarge(_) => 413,
83            Error::UnsupportedMediaType(_) => 415,
84            Error::Problem(problem) => problem.status,
85        }
86    }
87}
88
89/// Shorthand for Result<T, Error>.
90pub type Result<T> = std::result::Result<T, Error>;