Skip to main content

serenade_http/
error.rs

1//! HTTP handler and kernel errors.
2
3/// Failure while handling a request.
4#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
5pub enum HttpError {
6    /// Handler failed without a specific status (maps to HTTP 500).
7    #[error("request handler failed: {0}")]
8    Failed(String),
9    /// Handler failed with an HTTP status to map onto the response.
10    #[error("HTTP {status}: {message}")]
11    Status {
12        /// Suggested status code.
13        status: u16,
14        /// Error text.
15        message: String,
16    },
17}
18
19impl HttpError {
20    /// Handler failure that maps to HTTP 500 by default.
21    #[must_use]
22    pub fn failed(message: impl Into<String>) -> Self {
23        Self::Failed(message.into())
24    }
25
26    /// Failure that maps to `status`.
27    #[must_use]
28    pub fn status(status: u16, message: impl Into<String>) -> Self {
29        Self::Status {
30            status,
31            message: message.into(),
32        }
33    }
34
35    /// Convenience: HTTP 404.
36    #[must_use]
37    pub fn not_found(message: impl Into<String>) -> Self {
38        Self::status(404, message)
39    }
40
41    /// Convenience: HTTP 400.
42    #[must_use]
43    pub fn bad_request(message: impl Into<String>) -> Self {
44        Self::status(400, message)
45    }
46
47    /// Convenience: HTTP 422.
48    #[must_use]
49    pub fn unprocessable(message: impl Into<String>) -> Self {
50        Self::status(422, message)
51    }
52
53    /// Status used by [`crate::DefaultExceptionHandler`].
54    #[must_use]
55    pub const fn status_code(&self) -> u16 {
56        match self {
57            Self::Failed(_) => 500,
58            Self::Status { status, .. } => *status,
59        }
60    }
61
62    /// Human-readable message (without the `HTTP {status}:` prefix).
63    #[must_use]
64    pub fn message(&self) -> &str {
65        match self {
66            Self::Failed(message) | Self::Status { message, .. } => message,
67        }
68    }
69}