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
92
93
94
95
use std::fmt;

use axum::{
    response::{IntoResponse, Response},
    Json,
};
use http::{header::LOCATION, StatusCode};
use log::error;
use serde::{Deserialize, Serialize};
use url::Url;

#[derive(Serialize, Deserialize)]
pub struct ErrorBody {
    pub message: String,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RedirectMode {
    MovedPermanently,
    #[default]
    Found,
    SeeOther,
    TemporaryRedirect,
    PermanentRedirect,
}

impl RedirectMode {
    pub fn status_code(&self) -> StatusCode {
        match self {
            RedirectMode::MovedPermanently => StatusCode::MOVED_PERMANENTLY,
            RedirectMode::Found => StatusCode::FOUND,
            RedirectMode::SeeOther => StatusCode::SEE_OTHER,
            RedirectMode::TemporaryRedirect => StatusCode::TEMPORARY_REDIRECT,
            RedirectMode::PermanentRedirect => StatusCode::PERMANENT_REDIRECT,
        }
    }
}

#[derive(Debug)]
pub enum ApiError {
    Redirect(RedirectMode, Url),
    NotModified,
    BadRequest(String),
    Unauthorized(String),
    Forbidden(String),
    NotFound,
    Response(Response),
    Other(anyhow::Error),
}

impl fmt::Display for ApiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <Self as fmt::Debug>::fmt(self, f)
    }
}

impl<E: std::error::Error + Send + Sync + 'static> From<E> for ApiError {
    fn from(error: E) -> Self {
        Self::Other(anyhow::Error::from(error))
    }
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        match self {
            ApiError::Redirect(mode, destination) => {
                (mode.status_code(), [(LOCATION, destination.to_string())]).into_response()
            }
            ApiError::NotModified => StatusCode::NOT_MODIFIED.into_response(),
            ApiError::BadRequest(message) => {
                (StatusCode::BAD_REQUEST, Json(ErrorBody { message })).into_response()
            }
            ApiError::Unauthorized(message) => {
                (StatusCode::UNAUTHORIZED, Json(ErrorBody { message })).into_response()
            }
            ApiError::Forbidden(message) => {
                (StatusCode::FORBIDDEN, Json(ErrorBody { message })).into_response()
            }
            ApiError::NotFound => (
                StatusCode::NOT_FOUND,
                Json(ErrorBody {
                    message: "not found".to_string(),
                }),
            )
                .into_response(),
            ApiError::Response(response) => response,
            ApiError::Other(e) => {
                error!("internal error: {:#}", e);
                StatusCode::INTERNAL_SERVER_ERROR.into_response()
            }
        }
    }
}

pub type ApiResult<T> = Result<T, ApiError>;