first commit

This commit is contained in:
Romulus21 committed 2026-10-26 13:21:14 +01:00
commit dd6a740645
37 files changed
+5424

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde_json::json;
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("ressource introuvable")]
NotFound,
#[error("{0}")]
Conflict(String),
#[error("{0}")]
Validation(String),
#[error("erreur de base de données")]
Db(#[source] sqlx::Error),
#[error("erreur interne")]
Internal(#[source] anyhow::Error),
}
pub type AppResult<T> = Result<T, AppError>;
impl AppError {
pub fn status(&self) -> StatusCode {
match self {
Self::NotFound => StatusCode::NOT_FOUND,
Self::Conflict(_) => StatusCode::CONFLICT,
Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
Self::Db(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
pub fn log(&self) {
match self {
Self::Db(e) => tracing::error!(error = %e, "database error"),
Self::Internal(e) => tracing::error!(error = %e, "internal error"),
_ => {}
}
}
}
impl From<sqlx::Error> for AppError {
fn from(e: sqlx::Error) -> Self {
match &e {
sqlx::Error::RowNotFound => Self::NotFound,
sqlx::Error::Database(db) if db.is_unique_violation() => {
Self::Conflict("cet élément existe déjà".into())
}
_ => Self::Db(e),
}
}
}
impl From<askama::Error> for AppError {
fn from(e: askama::Error) -> Self {
Self::Internal(e.into())
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
self.log();
(self.status(), Json(json!({ "error": self.to_string() }))).into_response()
}
}