use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCode {
NotFound,
BadRequest,
Unauthenticated,
Forbidden,
PasswordRequired,
MethodNotAllowed,
RateLimited,
Unavailable,
Internal,
}
impl ErrorCode {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::NotFound => "not_found",
Self::BadRequest => "bad_request",
Self::Unauthenticated => "unauthenticated",
Self::Forbidden => "forbidden",
Self::PasswordRequired => "password_required",
Self::MethodNotAllowed => "method_not_allowed",
Self::RateLimited => "rate_limited",
Self::Unavailable => "unavailable",
Self::Internal => "internal_error",
}
}
#[must_use]
pub fn status(self) -> StatusCode {
match self {
Self::NotFound => StatusCode::NOT_FOUND,
Self::BadRequest => StatusCode::BAD_REQUEST,
Self::Unauthenticated => StatusCode::UNAUTHORIZED,
Self::Forbidden | Self::PasswordRequired => StatusCode::FORBIDDEN,
Self::MethodNotAllowed => StatusCode::METHOD_NOT_ALLOWED,
Self::RateLimited => StatusCode::TOO_MANY_REQUESTS,
Self::Unavailable => StatusCode::SERVICE_UNAVAILABLE,
Self::Internal => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
#[derive(Debug, Clone)]
pub struct ApiError {
pub code: ErrorCode,
pub message: String,
}
impl ApiError {
#[must_use]
pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
}
}
#[must_use]
pub fn not_found(what: &str) -> Self {
Self::new(ErrorCode::NotFound, format!("{what} not found"))
}
#[must_use]
pub fn bad_request(message: impl Into<String>) -> Self {
Self::new(ErrorCode::BadRequest, message)
}
#[must_use]
pub fn internal() -> Self {
Self::new(ErrorCode::Internal, "internal error")
}
#[must_use]
pub fn unauthenticated() -> Self {
Self::new(
ErrorCode::Unauthenticated,
"authentication required to view this page",
)
}
#[must_use]
pub fn forbidden() -> Self {
Self::new(ErrorCode::Forbidden, "you don't have access to this page")
}
#[must_use]
pub fn password_required() -> Self {
Self::new(
ErrorCode::PasswordRequired,
"this page is password-protected",
)
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
(
self.code.status(),
Json(serde_json::json!({
"error": { "code": self.code.as_str(), "message": self.message }
})),
)
.into_response()
}
}
pub async fn method_not_allowed_json(
req: axum::extract::Request,
next: axum::middleware::Next,
) -> Response {
let resp = next.run(req).await;
if resp.status() != StatusCode::METHOD_NOT_ALLOWED {
return resp;
}
let (parts, _) = resp.into_parts();
let mut out = ApiError::new(ErrorCode::MethodNotAllowed, "method not allowed").into_response();
for (name, value) in parts.headers {
let Some(name) = name else { continue };
if name == axum::http::header::CONTENT_LENGTH
|| name == axum::http::header::CONTENT_TYPE
{
continue;
}
out.headers_mut().insert(name, value);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_code_maps_to_one_status() {
assert_eq!(ErrorCode::NotFound.status(), StatusCode::NOT_FOUND);
assert_eq!(ErrorCode::BadRequest.status(), StatusCode::BAD_REQUEST);
assert_eq!(ErrorCode::Unauthenticated.status(), StatusCode::UNAUTHORIZED);
assert_eq!(ErrorCode::Forbidden.status(), StatusCode::FORBIDDEN);
assert_eq!(ErrorCode::PasswordRequired.status(), StatusCode::FORBIDDEN);
assert_eq!(ErrorCode::RateLimited.status(), StatusCode::TOO_MANY_REQUESTS);
assert_eq!(ErrorCode::Unavailable.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(
ErrorCode::Internal.status(),
StatusCode::INTERNAL_SERVER_ERROR,
);
}
#[test]
fn codes_are_stable_snake_case_identifiers() {
for (code, want) in [
(ErrorCode::NotFound, "not_found"),
(ErrorCode::BadRequest, "bad_request"),
(ErrorCode::Unauthenticated, "unauthenticated"),
(ErrorCode::Forbidden, "forbidden"),
(ErrorCode::PasswordRequired, "password_required"),
(ErrorCode::Internal, "internal_error"),
(ErrorCode::MethodNotAllowed, "method_not_allowed"),
(ErrorCode::RateLimited, "rate_limited"),
(ErrorCode::Unavailable, "unavailable"),
] {
assert_eq!(code.as_str(), want);
}
}
#[test]
fn not_found_reads_naturally_and_hides_the_reason() {
assert_eq!(ApiError::not_found("page").message, "page not found");
assert_eq!(ApiError::not_found("menu").message, "menu not found");
}
}