Return JSON error responses.

This commit is contained in:
2026-09-25 17:32:54 +02:00
parent 4cf6bd2f14
commit 37a2b7b5dc
7 changed files with 92 additions and 16 deletions
+27 -4
View File
@@ -17,6 +17,9 @@ use crate::routes::{
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("bad request")]
BadRequest(String),
#[error("not found")]
NotFound,
@@ -42,14 +45,17 @@ pub enum AppError {
impl IntoResponse for AppError {
fn into_response(self) -> Response {
match self {
Self::BadRequest(error) => {
return error_response(StatusCode::BAD_REQUEST, error);
}
Self::NotFound => {
return StatusCode::NOT_FOUND.into_response();
return error_response(StatusCode::NOT_FOUND, "Not found");
}
Self::ScheduledTransactionValidation(error) => {
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response();
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
}
Self::TransactionValidation(error) => {
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response();
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
}
Self::Database(error) => {
tracing::error!(%error, "Database query failed");
@@ -65,6 +71,23 @@ impl IntoResponse for AppError {
}
}
(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error").into_response()
error_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
}
}
#[derive(serde::Serialize)]
pub struct ErrorResponse {
pub message: String,
}
impl ErrorResponse {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
fn error_response(status_code: StatusCode, message: impl Into<String>) -> Response {
(status_code, axum::Json(ErrorResponse::new(message))).into_response()
}