about summary refs log tree commit diff
path: root/src/error.rs
blob: eb589186993cedf75592f934ecf80b2a9d0ed366 (plain)
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
//! Shared error response shape for all endpoints, modeled on RFC 7807
//! (Problem Details for HTTP APIs) plus a few extra fields: a machine
//! readable `code`, the OpenAPI `operation_id` that failed, a `spec_url`
//! pointing back at /openapi.json, the request's `request_id` (see the
//! SetRequestIdLayer/PropagateRequestIdLayer in lib.rs), and `next`, a
//! hint at a related endpoint the caller might try instead.
//!
//! `type`/`spec_url` are relative paths, not absolute URLs, since this
//! service has no fixed public domain; RFC 7807 explicitly allows `type`
//! to be a relative URI reference.

use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::Serialize;

#[derive(Debug, Serialize, utoipa::ToSchema)]
pub struct ApiError {
    pub r#type: String,
    pub title: String,
    pub status: u16,
    pub code: String,
    pub detail: String,
    pub operation_id: String,
    pub spec_url: String,
    pub request_id: Option<String>,
    pub next: Option<String>,
}

impl ApiError {
    pub fn new(
        status: StatusCode,
        code: &str,
        title: &str,
        detail: String,
        operation_id: &str,
    ) -> Self {
        ApiError {
            r#type: format!("/errors/{code}"),
            title: title.to_string(),
            status: status.as_u16(),
            code: code.to_string(),
            detail,
            operation_id: operation_id.to_string(),
            spec_url: "/openapi.json".to_string(),
            request_id: None,
            next: None,
        }
    }

    pub fn with_request_id(mut self, request_id: Option<String>) -> Self {
        self.request_id = request_id;
        self
    }

    pub fn with_next(mut self, next: &str) -> Self {
        self.next = Some(next.to_string());
        self
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        (status, Json(self)).into_response()
    }
}

/// The 401 every token-gated endpoint can return, as one shared
/// `IntoResponses` type (an `ApiError` body under the hood) instead of
/// writing out `(status = 401, description = "...", body = ApiError)`
/// by hand on each `#[utoipa::path(...)]` -- reference it bare inside
/// `responses(...)`, e.g. `responses(Unauthorized, (status = 200, ...))`.
/// Which endpoints actually need it (i.e. take `AuthToken`) is still a
/// per-handler decision; this only removes the repetition in
/// documenting the one response shape that decision implies.
#[derive(utoipa::IntoResponses)]
#[response(status = 401, description = "Missing or invalid token")]
#[allow(dead_code)] // only ever used for its OpenAPI schema, never constructed
pub struct Unauthorized(#[to_schema] ApiError);