Skip to main content

opendev_web/
error.rs

1//! Error types for the web server.
2
3use axum::http::StatusCode;
4use axum::response::{IntoResponse, Response};
5use serde_json::json;
6
7/// Web server error type.
8#[derive(Debug, thiserror::Error)]
9pub enum WebError {
10    #[error("not found: {0}")]
11    NotFound(String),
12
13    #[error("bad request: {0}")]
14    BadRequest(String),
15
16    #[error("unauthorized: {0}")]
17    Unauthorized(String),
18
19    #[error("conflict: {0}")]
20    Conflict(String),
21
22    #[error("internal error: {0}")]
23    Internal(String),
24
25    #[error("session error: {0}")]
26    Session(#[from] std::io::Error),
27
28    #[error("serialization error: {0}")]
29    Serialization(#[from] serde_json::Error),
30}
31
32impl IntoResponse for WebError {
33    fn into_response(self) -> Response {
34        let (status, message) = match &self {
35            WebError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
36            WebError::BadRequest(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
37            WebError::Unauthorized(msg) => (StatusCode::UNAUTHORIZED, msg.clone()),
38            WebError::Conflict(msg) => (StatusCode::CONFLICT, msg.clone()),
39            WebError::Internal(msg) => (StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
40            WebError::Session(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
41            WebError::Serialization(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
42        };
43
44        let body = json!({
45            "error": message,
46        });
47
48        (status, axum::Json(body)).into_response()
49    }
50}