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
48impl Error {
49    /// Map the error to an appropriate HTTP status code.
50    ///
51    /// Used by the built-in exception middleware to produce
52    /// well-formed HTTP error responses.
53    pub fn status_code(&self) -> u16 {
54        match self {
55            Error::Http(_) => 400,
56            Error::Status(code, _) => *code,
57            Error::Unauthorized(_) => 401,
58            Error::Forbidden(_) => 403,
59            Error::Di(_) => 500,
60            Error::Routing(_) => 404,
61            Error::Serialization(_) => 400,
62            Error::Internal(_) => 500,
63            Error::Message(_) => 500,
64            Error::Validation(_) => 400,
65            Error::NotFound(_) => 404,
66            Error::Conflict(_) => 409,
67        }
68    }
69}
70
71/// Shorthand for Result<T, Error>.
72pub type Result<T> = std::result::Result<T, Error>;