use axum::http::StatusCode; use axum::response::{IntoResponse, Response}; use axum::Json; use serde_json::json; #[derive(Debug, thiserror::Error)] pub enum AppError { #[error("not found")] NotFound, #[error("bad request: {0}")] BadRequest(String), #[error(transparent)] Sqlx(#[from] sqlx::Error), #[error(transparent)] Reqwest(#[from] reqwest::Error), #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] Anyhow(#[from] anyhow::Error), #[error("internal: {0}")] Internal(String), } impl IntoResponse for AppError { fn into_response(self) -> Response { let (code, msg) = match &self { AppError::NotFound => (StatusCode::NOT_FOUND, "not_found".to_string()), AppError::BadRequest(m) => (StatusCode::BAD_REQUEST, m.clone()), AppError::Sqlx(sqlx::Error::RowNotFound) => { (StatusCode::NOT_FOUND, "not_found".to_string()) } _ => { tracing::error!("internal: {self:?}"); ( StatusCode::INTERNAL_SERVER_ERROR, "internal_error".to_string(), ) } }; (code, Json(json!({ "error": msg }))).into_response() } } pub type AppResult = Result;