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)] #[derive(Debug, thiserror::Error)]
pub enum AppError { pub enum AppError {
#[error("bad request")]
BadRequest(String),
#[error("not found")] #[error("not found")]
NotFound, NotFound,
@@ -42,14 +45,17 @@ pub enum AppError {
impl IntoResponse for AppError { impl IntoResponse for AppError {
fn into_response(self) -> Response { fn into_response(self) -> Response {
match self { match self {
Self::BadRequest(error) => {
return error_response(StatusCode::BAD_REQUEST, error);
}
Self::NotFound => { Self::NotFound => {
return StatusCode::NOT_FOUND.into_response(); return error_response(StatusCode::NOT_FOUND, "Not found");
} }
Self::ScheduledTransactionValidation(error) => { Self::ScheduledTransactionValidation(error) => {
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(); return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
} }
Self::TransactionValidation(error) => { Self::TransactionValidation(error) => {
return (StatusCode::UNPROCESSABLE_ENTITY, error.to_string()).into_response(); return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
} }
Self::Database(error) => { Self::Database(error) => {
tracing::error!(%error, "Database query failed"); 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()
}
+3 -2
View File
@@ -1,6 +1,7 @@
pub mod dtos; pub mod dtos;
mod scheduled_transactions; pub mod extractors;
mod transactions; pub mod scheduled_transactions;
pub mod transactions;
pub mod validation; pub mod validation;
pub fn create_router(pool: sqlx::PgPool) -> axum::Router { pub fn create_router(pool: sqlx::PgPool) -> axum::Router {
+2
View File
@@ -0,0 +1,2 @@
pub mod json;
pub mod path;
+32
View File
@@ -0,0 +1,32 @@
use axum::extract::{FromRequest, Request};
use axum::response::IntoResponse;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::error::AppError;
pub struct Json<T>(pub T);
impl<T, S> FromRequest<S> for Json<T>
where
T: DeserializeOwned,
S: Send + Sync,
{
type Rejection = AppError;
async fn from_request(request: Request, state: &S) -> Result<Self, Self::Rejection> {
axum::Json::<T>::from_request(request, state)
.await
.map(|axum::Json(value)| Self(value))
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
}
}
impl<T> IntoResponse for Json<T>
where
T: Serialize,
{
fn into_response(self) -> axum::response::Response {
axum::Json(self.0).into_response()
}
}
+24
View File
@@ -0,0 +1,24 @@
use axum::extract::FromRequestParts;
use serde::de::DeserializeOwned;
use crate::error::AppError;
pub struct Path<T>(pub T);
impl<T, S> FromRequestParts<S> for Path<T>
where
T: DeserializeOwned + Send,
S: Send + Sync,
{
type Rejection = AppError;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
axum::extract::Path::<T>::from_request_parts(parts, state)
.await
.map(|axum::extract::Path(value)| Self(value))
.map_err(|rejection| AppError::BadRequest(rejection.body_text()))
}
}
+2 -5
View File
@@ -1,8 +1,4 @@
use axum::{ use axum::{extract::State, http::StatusCode};
Json,
extract::{Path, State},
http::StatusCode,
};
use sqlx::PgPool; use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
@@ -20,6 +16,7 @@ use crate::{
dtos::scheduled_transaction::{ dtos::scheduled_transaction::{
RecurringTransaction, ScheduledTransaction, ScheduledTransactionData, RecurringTransaction, ScheduledTransaction, ScheduledTransactionData,
}, },
extractors::{json::Json, path::Path},
validation::scheduled_transaction::ValidatedRecurringTransaction, validation::scheduled_transaction::ValidatedRecurringTransaction,
}, },
}; };
+2 -5
View File
@@ -1,8 +1,4 @@
use axum::{ use axum::{extract::State, http::StatusCode};
Json,
extract::{Path, State},
http::StatusCode,
};
use sqlx::PgPool; use sqlx::PgPool;
use uuid::Uuid; use uuid::Uuid;
@@ -17,6 +13,7 @@ use crate::{
error::AppError, error::AppError,
routes::{ routes::{
dtos::transaction::{Transaction, TransactionData}, dtos::transaction::{Transaction, TransactionData},
extractors::{json::Json, path::Path},
validation::transaction::ValidatedTransaction, validation::transaction::ValidatedTransaction,
}, },
}; };