Skip to main content

systemprompt_models/errors/
service.rs

1//! Application-layer service umbrella error and its conversions into
2//! the public [`crate::api::ApiError`] HTTP shape.
3
4use systemprompt_traits::RepositoryError;
5
6use crate::api::ApiError;
7
8#[derive(Debug, thiserror::Error)]
9pub enum ServiceError {
10    #[error("repository error: {0}")]
11    Repository(#[from] RepositoryError),
12
13    #[error("validation error: {0}")]
14    Validation(String),
15
16    #[error("business logic error: {0}")]
17    BusinessLogic(String),
18
19    #[error("external service error: {0}")]
20    External(String),
21
22    #[error("not found: {0}")]
23    NotFound(String),
24
25    #[error("conflict: {0}")]
26    Conflict(String),
27
28    #[error("unauthorized: {0}")]
29    Unauthorized(String),
30
31    #[error("forbidden: {0}")]
32    Forbidden(String),
33}
34
35impl From<ServiceError> for ApiError {
36    fn from(err: ServiceError) -> Self {
37        match err {
38            ServiceError::Repository(e) => e.into(),
39            ServiceError::Validation(msg) | ServiceError::BusinessLogic(msg) => {
40                Self::bad_request(msg)
41            },
42            ServiceError::NotFound(msg) => Self::not_found(msg),
43            ServiceError::External(msg) => {
44                Self::internal_error(format!("External service error: {msg}"))
45            },
46            ServiceError::Conflict(msg) => Self::conflict(msg),
47            ServiceError::Unauthorized(msg) => Self::unauthorized(msg),
48            ServiceError::Forbidden(msg) => Self::forbidden(msg),
49        }
50    }
51}
52
53impl From<RepositoryError> for ApiError {
54    fn from(err: RepositoryError) -> Self {
55        match err {
56            RepositoryError::NotFound(msg) => Self::not_found(msg),
57            RepositoryError::InvalidData(msg) | RepositoryError::ConstraintViolation(msg) => {
58                Self::bad_request(msg)
59            },
60            RepositoryError::Database(e) => Self::internal_error(format!("Database error: {e}")),
61            RepositoryError::Serialization(e) => {
62                Self::internal_error(format!("Serialization error: {e}"))
63            },
64            RepositoryError::Other(e) => Self::internal_error(format!("Error: {e}")),
65            _ => Self::internal_error(format!("Repository error: {err}")),
66        }
67    }
68}