Restructured client error impls.

This commit is contained in:
2026-10-11 08:23:07 +02:00
parent 02f29f3a99
commit 728c9fd3d9
3 changed files with 162 additions and 163 deletions
+1 -163
View File
@@ -1,15 +1,4 @@
use std::borrow::Cow; use crate::{domain::DomainError, repository::RepositoryError, routes::extractors::ExtractorError};
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use crate::{
domain::DomainError,
repository::RepositoryError,
routes::extractors::{AuthError, AuthHeaderError, BearerError, ExtractorError},
};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum AppError { pub enum AppError {
@@ -40,154 +29,3 @@ pub enum AppError {
#[error(transparent)] #[error(transparent)]
Internal(#[from] anyhow::Error), Internal(#[from] anyhow::Error),
} }
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = self.client_response();
if status.is_server_error() {
tracing::error!(error = ?self, %status, "request failed");
} else {
tracing::debug!(error = ?self, %status, "request rejected");
}
error_response(status, message)
}
}
impl ClientError for AppError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::InvalidClientCredentials => (
StatusCode::UNAUTHORIZED,
"Invalid client credentials".into(),
),
Self::InvalidRefreshToken => (StatusCode::UNAUTHORIZED, "Invalid refresh token".into()),
Self::AppIdAlreadyExists => (StatusCode::CONFLICT, "App ID already exists".into()),
Self::NotFound => (StatusCode::NOT_FOUND, "Not found".into()),
Self::Domain(error) => error.client_response(),
Self::Extractor(error) => error.client_response(),
Self::Repository(error) => error.client_response(),
Self::Internal(_) | Self::Unknown => internal_error(),
}
}
}
impl ClientError for ExtractorError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::Authorization(error) => error.client_response(),
Self::Form(_) => (StatusCode::BAD_REQUEST, "Form error".into()),
Self::Json(_) => (StatusCode::BAD_REQUEST, "Json error".into()),
Self::Path(_) => (StatusCode::BAD_REQUEST, "Path error".into()),
Self::Query(_) => (StatusCode::BAD_REQUEST, "Query error".into()),
}
}
}
impl ClientError for AuthError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::UnsupportedScheme => (StatusCode::UNAUTHORIZED, "Unsupported scheme".into()),
Self::Bearer(error) => error.client_response(),
Self::Header(error) => error.client_response(),
Self::Repository(error) => error.client_response(),
}
}
}
impl ClientError for BearerError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::InvalidCredentials => (StatusCode::UNAUTHORIZED, "Invalid credentials".into()),
Self::Repository(error) => error.client_response(),
}
}
}
impl ClientError for AuthHeaderError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
let message = match self {
Self::Missing => "Missing authorization header",
Self::NotAscii(_) => "Invalid authorization header encoding",
Self::MalformedValue => "Malformed authorization header",
Self::EmptyScheme => "Empty authorization scheme",
Self::EmptyToken => "Empty authorization token",
};
(StatusCode::UNAUTHORIZED, message.into())
}
}
impl ClientError for DomainError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
let message: String = match self {
Self::Amount(error) => error.to_string(),
Self::Schedule(error) => error.to_string(),
Self::UserAppSecret(error) => error.to_string(),
};
(StatusCode::UNPROCESSABLE_ENTITY, message.into())
}
}
impl ClientError for RepositoryError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::Database(_) | Self::Decode(_) => internal_error(),
Self::QueryConversion(error) => (StatusCode::BAD_REQUEST, error.to_string().into()),
Self::ReferenceViolation { relation, kind, .. } => {
use crate::repository::{
ReferenceRelation as Relation, ReferenceViolationKind as Kind,
};
match (relation, kind) {
(Relation::Account, Kind::Missing) => (
StatusCode::UNPROCESSABLE_ENTITY,
"Account cannot be found".into(),
),
(Relation::RecurringTransaction, Kind::StillReferenced) => (
StatusCode::CONFLICT,
"Still referenced by one or more recurring transactions".into(),
),
(Relation::Transaction, Kind::StillReferenced) => (
StatusCode::CONFLICT,
"Still referenced by one or more transactions".into(),
),
(Relation::User, Kind::Missing) => {
(StatusCode::NOT_FOUND, "User cannot be found".into())
}
(Relation::UserApp, Kind::Missing) => {
(StatusCode::NOT_FOUND, "User app cannot be found".into())
}
_ => internal_error(),
}
}
}
}
}
trait ClientError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>);
}
fn internal_error() -> (StatusCode, Cow<'static, str>) {
(
StatusCode::INTERNAL_SERVER_ERROR,
"Internal server error".into(),
)
}
#[derive(serde::Serialize)]
struct ErrorResponse {
pub message: String,
}
fn error_response(status_code: StatusCode, message: impl Into<String>) -> Response {
(
status_code,
axum::Json(ErrorResponse {
message: message.into(),
}),
)
.into_response()
}
+1
View File
@@ -6,6 +6,7 @@ mod accounts;
mod auth_passkey; mod auth_passkey;
mod auth_token; mod auth_token;
mod dtos; mod dtos;
mod errors;
pub mod extractors; pub mod extractors;
mod scheduled_transactions; mod scheduled_transactions;
mod transactions; mod transactions;
+160
View File
@@ -0,0 +1,160 @@
use std::borrow::Cow;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use super::extractors::{AuthError, AuthHeaderError, BearerError, ExtractorError};
use crate::{domain::DomainError, error::AppError, repository::RepositoryError};
impl ClientError for AppError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::InvalidClientCredentials => (
StatusCode::UNAUTHORIZED,
"Invalid client credentials".into(),
),
Self::InvalidRefreshToken => (StatusCode::UNAUTHORIZED, "Invalid refresh token".into()),
Self::AppIdAlreadyExists => (StatusCode::CONFLICT, "App ID already exists".into()),
Self::NotFound => (StatusCode::NOT_FOUND, "Not found".into()),
Self::Domain(error) => error.client_response(),
Self::Extractor(error) => error.client_response(),
Self::Repository(error) => error.client_response(),
Self::Internal(_) | Self::Unknown => internal_error(),
}
}
}
impl ClientError for DomainError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
let message: String = match self {
Self::Amount(error) => error.to_string(),
Self::Schedule(error) => error.to_string(),
Self::UserAppSecret(error) => error.to_string(),
};
(StatusCode::UNPROCESSABLE_ENTITY, message.into())
}
}
impl ClientError for ExtractorError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::Authorization(error) => error.client_response(),
Self::Form(_) => (StatusCode::BAD_REQUEST, "Form error".into()),
Self::Json(_) => (StatusCode::BAD_REQUEST, "Json error".into()),
Self::Path(_) => (StatusCode::BAD_REQUEST, "Path error".into()),
Self::Query(_) => (StatusCode::BAD_REQUEST, "Query error".into()),
}
}
}
impl ClientError for AuthError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::UnsupportedScheme => (StatusCode::UNAUTHORIZED, "Unsupported scheme".into()),
Self::Bearer(error) => error.client_response(),
Self::Header(error) => error.client_response(),
Self::Repository(error) => error.client_response(),
}
}
}
impl ClientError for BearerError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::InvalidCredentials => (StatusCode::UNAUTHORIZED, "Invalid credentials".into()),
Self::Repository(error) => error.client_response(),
}
}
}
impl ClientError for AuthHeaderError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
let message = match self {
Self::Missing => "Missing authorization header",
Self::NotAscii(_) => "Invalid authorization header encoding",
Self::MalformedValue => "Malformed authorization header",
Self::EmptyScheme => "Empty authorization scheme",
Self::EmptyToken => "Empty authorization token",
};
(StatusCode::UNAUTHORIZED, message.into())
}
}
impl ClientError for RepositoryError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>) {
match self {
Self::Database(_) | Self::Decode(_) => internal_error(),
Self::QueryConversion(error) => (StatusCode::BAD_REQUEST, error.to_string().into()),
Self::ReferenceViolation { relation, kind, .. } => {
use crate::repository::{
ReferenceRelation as Relation, ReferenceViolationKind as Kind,
};
match (relation, kind) {
(Relation::Account, Kind::Missing) => (
StatusCode::UNPROCESSABLE_ENTITY,
"Account cannot be found".into(),
),
(Relation::RecurringTransaction, Kind::StillReferenced) => (
StatusCode::CONFLICT,
"Still referenced by one or more recurring transactions".into(),
),
(Relation::Transaction, Kind::StillReferenced) => (
StatusCode::CONFLICT,
"Still referenced by one or more transactions".into(),
),
(Relation::User, Kind::Missing) => {
(StatusCode::NOT_FOUND, "User cannot be found".into())
}
(Relation::UserApp, Kind::Missing) => {
(StatusCode::NOT_FOUND, "User app cannot be found".into())
}
_ => internal_error(),
}
}
}
}
}
trait ClientError {
fn client_response(&self) -> (StatusCode, Cow<'_, str>);
}
fn internal_error() -> (StatusCode, Cow<'static, str>) {
(
StatusCode::INTERNAL_SERVER_ERROR,
"Internal server error".into(),
)
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = self.client_response();
if status.is_server_error() {
tracing::error!(error = ?self, %status, "request failed");
} else {
tracing::debug!(error = ?self, %status, "request rejected");
}
error_response(status, message)
}
}
#[derive(serde::Serialize)]
struct ErrorResponse {
pub message: String,
}
fn error_response(status_code: StatusCode, message: impl Into<String>) -> Response {
(
status_code,
axum::Json(ErrorResponse {
message: message.into(),
}),
)
.into_response()
}