Registry / RepositoryTypeScriptRustPython
Rollpie
ReadmeFiles
Versions
Info
Download
0.1.280.1 KB2026-09-140.1.167.6 KB2026-09-140.1.064.9 KB2026-09-14
Version
0.1.0
Copyright
Rollpie, Irohabook
Publisher
math
Published
2026-09-14
Size
64.9 KB
Downloads
2
Checksum
3f5a7260ef28c5f7ca3540b87faa9176bdf8039ad720f809e49a0f7117b8528b
Dependencies
None

error.rs

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
85
86
87
88
89
90
91
//! アプリ共通のエラー型。どの経路で失敗しても `{"error": "..."}` の JSON で返す

use axum::Json;
use axum::extract::rejection::{JsonRejection, PathRejection, QueryRejection};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::Serialize;


/// どこで失敗しても、これに集めて JSON で返す
#[derive(Debug, thiserror::Error)]
pub enum AppError {
    /// 404
    #[error("{0}")]
    NotFound(String),

    /// 422: 入力値の検証に失敗した
    #[error("{0}")]
    Validation(String),

    /// 400 など: リクエストボディの JSON が不正
    #[error(transparent)]
    Json(#[from] JsonRejection),

    /// 400: パスパラメータの型が合わない
    #[error(transparent)]
    Path(#[from] PathRejection),

    /// 400: クエリ文字列の型が合わない
    #[error(transparent)]
    Query(#[from] QueryRejection),

    /// 502: 中継先が応答しない、または応答が壊れている
    #[error(transparent)]
    Relay(#[from] reqwest::Error),

    /// 500: データベースの失敗
    #[error(transparent)]
    Database(#[from] sqlx::Error),

    /// 500: 想定外のエラー。`?` で anyhow::Error から自動変換される
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

#[derive(Serialize)]
struct ErrorBody {
    error: String,
}


/// status と文言から、他と同じ形の JSON を組み立てる。
///
/// [`AppError`] を通らない経路から使う。ミドルウェアが自分で返す応答がそれにあたる。
pub fn json(status: StatusCode, message: &str) -> Response {
    (status, Json(ErrorBody {error: message.to_owned()})).into_response()
}


impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            Self::NotFound(message) => (StatusCode::NOT_FOUND, message),
            Self::Validation(message) => (StatusCode::UNPROCESSABLE_ENTITY, message),
            Self::Json(rejection) => (rejection.status(), rejection.body_text()),
            Self::Path(rejection) => (rejection.status(), rejection.body_text()),
            Self::Query(rejection) => (rejection.status(), rejection.body_text()),
            // 時間切れとつながらないのを分ける。前段の記録で原因が読み分けられる
            Self::Relay(error) => {
                tracing::error!(error = ?error, "relay failed");
                if error.is_timeout() {
                    (StatusCode::GATEWAY_TIMEOUT, "gateway timeout".to_owned())
                } else {
                    (StatusCode::BAD_GATEWAY, "bad gateway".to_owned())
                }
            }

            // 内部の詳細はクライアントに返さず、ログにだけ残す
            Self::Database(error) => {
                tracing::error!(error = ?error, "database error");
                (StatusCode::INTERNAL_SERVER_ERROR, "internal server error".to_owned())
            }

            Self::Internal(error) => {
                tracing::error!(error = ?error, "unhandled error");
                (StatusCode::INTERNAL_SERVER_ERROR, "internal server error".to_owned())
            }
        };
        json(status, &message)
    }
}