106 lines
3.4 KiB
Rust
106 lines
3.4 KiB
Rust
use axum::{
|
|
http::StatusCode,
|
|
response::{IntoResponse, Response},
|
|
};
|
|
|
|
use crate::{
|
|
domain::DomainError,
|
|
repository::{ReferenceRelation, ReferenceViolationKind, RepositoryError},
|
|
};
|
|
|
|
#[derive(Debug, thiserror::Error)]
|
|
pub enum AppError {
|
|
#[error("bad request")]
|
|
BadRequest(String),
|
|
|
|
#[error("not found")]
|
|
NotFound,
|
|
|
|
#[error("domain error")]
|
|
Domain(#[from] DomainError),
|
|
|
|
#[error("repository error")]
|
|
Repository(#[from] RepositoryError),
|
|
}
|
|
|
|
impl IntoResponse for AppError {
|
|
fn into_response(self) -> Response {
|
|
match self {
|
|
Self::BadRequest(error) => {
|
|
return error_response(StatusCode::BAD_REQUEST, error);
|
|
}
|
|
Self::NotFound => {
|
|
return error_response(StatusCode::NOT_FOUND, "Not found");
|
|
}
|
|
Self::Domain(error) => {
|
|
return error_response(StatusCode::UNPROCESSABLE_ENTITY, error.to_string());
|
|
}
|
|
Self::Repository(RepositoryError::Database(error)) => {
|
|
tracing::error!(%error, "Database query failed");
|
|
}
|
|
Self::Repository(RepositoryError::Decode(error)) => {
|
|
tracing::error!(%error, "Invalid stored data");
|
|
}
|
|
Self::Repository(RepositoryError::ReferenceViolation {
|
|
relation: ReferenceRelation::SourceAccount,
|
|
kind: ReferenceViolationKind::Missing,
|
|
..
|
|
}) => {
|
|
return error_response(
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
"Source account cannot be found",
|
|
);
|
|
}
|
|
Self::Repository(RepositoryError::ReferenceViolation {
|
|
relation: ReferenceRelation::DestinationAccount,
|
|
kind: ReferenceViolationKind::Missing,
|
|
..
|
|
}) => {
|
|
return error_response(
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
"Destination account cannot be found",
|
|
);
|
|
}
|
|
Self::Repository(RepositoryError::ReferenceViolation {
|
|
relation: ReferenceRelation::RecurringTransaction,
|
|
kind: ReferenceViolationKind::StillReferenced,
|
|
..
|
|
}) => {
|
|
return error_response(
|
|
StatusCode::CONFLICT,
|
|
"Still referenced by one or more recurring transactions",
|
|
);
|
|
}
|
|
Self::Repository(RepositoryError::ReferenceViolation {
|
|
relation,
|
|
kind,
|
|
source,
|
|
}) => {
|
|
tracing::error!(%relation, %kind, error = ?source, "Unhandled reference violation");
|
|
}
|
|
Self::Repository(RepositoryError::QueryConversion(error)) => {
|
|
return error_response(StatusCode::BAD_REQUEST, error.to_string());
|
|
}
|
|
}
|
|
|
|
error_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")
|
|
}
|
|
}
|
|
|
|
#[derive(serde::Serialize)]
|
|
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()
|
|
}
|