forked from Txio-labs/txio-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
84 lines (70 loc) · 2.7 KB
/
Copy patherror.rs
File metadata and controls
84 lines (70 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Database error: {0}")]
Database(#[from] mongodb::error::Error),
#[error("Configuration error: {0}")]
Config(#[from] config::ConfigError),
#[error("Not found: {0}")]
NotFound(String),
#[error("Unauthorized: {0}")]
Unauthorized(String),
#[error("Validation error: {0}")]
ValidationError(String),
#[error("Bad request: {0}")]
BadRequest(String),
#[error("Internal server error: {0}")]
InternalError(String),
#[error("External service error: {0}")]
ExternalService(String),
#[error("Forbidden: {0}")]
Forbidden(String),
}
impl AppError {
/// The status code and user-facing message for this error, in one place
/// so redirect-based flows (OAuth callbacks) and JSON responses stay
/// consistent — internals (DB/config/internal errors) are logged but
/// never leaked to the client either way.
pub fn status_and_message(&self) -> (StatusCode, &str) {
match self {
AppError::Database(e) => {
tracing::error!("Database error: {}", e);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
}
AppError::Config(_) => (StatusCode::INTERNAL_SERVER_ERROR, "Configuration error"),
AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.as_str()),
AppError::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, msg.as_str()),
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.as_str()),
AppError::Forbidden(msg) => (StatusCode::FORBIDDEN, msg.as_str()),
AppError::ValidationError(msg) => (StatusCode::BAD_REQUEST, msg.as_str()),
AppError::InternalError(msg) => {
tracing::error!("Internal error: {}", msg);
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
}
AppError::ExternalService(msg) => {
tracing::error!("External service error: {}", msg);
(StatusCode::BAD_GATEWAY, "External service unavailable")
}
}
}
/// The user-facing message alone, e.g. for building an OAuth error
/// redirect where there's no JSON body to carry a status code.
pub fn user_message(&self) -> &str {
self.status_and_message().1
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, error_message) = self.status_and_message();
let body = Json(json!({
"error": error_message,
}));
(status, body).into_response()
}
}