Skip to main content

shared_framework/controller/
errors.rs

1//! Controller result helpers: shortcuts for common success and error outcomes.
2//!
3//! [`Okay`] builds 200 [`ServiceResult`](crate::response::ServiceResult) values,
4//! while the error types build [`ErrorResult`](crate::response::ErrorResult)
5//! values with fixed status codes. Return them directly from handlers, whose
6//! convention is `Fn(CorrelationContext)` returning
7//! `Result<ServiceResult<T>, ErrorResult>`.
8//! ```ignore
9//! async fn get_user(ctx: CorrelationContext) -> Result<ServiceResult<User>, ErrorResult> {
10//!     Ok(Okay::result(user))
11//! }
12//! ```
13
14use crate::response::{ErrorResult, ServiceResult};
15
16/// Success-result shortcuts: builds 200 `ServiceResult` values for handlers.
17pub struct Okay;
18impl Okay {
19    /// Builds a 200 success result carrying `data` with message `"OK"`.
20    pub fn result<T: serde::Serialize>(data: T) -> ServiceResult<T> { ServiceResult::ok("OK", data) }
21    /// Builds a 200 success result with no payload and message `"OK"`.
22    pub fn empty() -> ServiceResult<()> { ServiceResult::new("success", "OK", None, 200) }
23}
24
25/// 401 error shortcut: builds an `ErrorResult` for failed authentication.
26pub struct AuthenticationError;
27impl AuthenticationError {
28    /// Builds a 401 `ErrorResult` with the given message.
29    pub fn new(msg: impl Into<String>) -> ErrorResult { ErrorResult::new(msg, None, 401) }
30}
31
32/// 403 error shortcut: builds an `ErrorResult` for denied authorization.
33pub struct AuthorizationError;
34impl AuthorizationError {
35    /// Builds a 403 `ErrorResult` with the given message.
36    pub fn new(msg: impl Into<String>) -> ErrorResult { ErrorResult::new(msg, None, 403) }
37}
38
39/// 500 error shortcut: builds an `ErrorResult` for invalid server configuration.
40pub struct BadConfiguration;
41impl BadConfiguration {
42    /// Builds a 500 `ErrorResult` with the given message.
43    pub fn new(msg: impl Into<String>) -> ErrorResult { ErrorResult::new(msg, None, 500) }
44}
45
46/// Custom-code error shortcut: builds an `ErrorResult` with a caller-chosen status.
47pub struct GenericError;
48impl GenericError {
49    /// Builds an `ErrorResult` with the given message and HTTP status `code`.
50    pub fn new(msg: impl Into<String>, code: u16) -> ErrorResult { ErrorResult::new(msg, None, code) }
51}