Refactor admin routes to use new AppError struct in responses

This commit is contained in:
Alphonse Paix
2025-09-20 01:08:05 +02:00
parent 01d2add44b
commit f5cd91108a
7 changed files with 86 additions and 75 deletions

View File

@@ -8,7 +8,10 @@ mod subscriptions_confirm;
pub use admin::*;
use askama::Template;
use axum::response::{Html, IntoResponse, Response};
use axum::{
http::HeaderMap,
response::{Html, IntoResponse, Response},
};
pub use health_check::*;
pub use home::*;
pub use login::*;
@@ -17,6 +20,62 @@ use reqwest::StatusCode;
pub use subscriptions::*;
pub use subscriptions_confirm::*;
use crate::templates::MessageTemplate;
#[derive(thiserror::Error)]
pub enum AppError {
#[error("An unexpected error was encountered.")]
UnexpectedError(#[from] anyhow::Error),
#[error("A validation error happened.")]
ValidationError(#[source] anyhow::Error),
#[error("An authentication is required.")]
NotAuthenticated,
}
impl std::fmt::Debug for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
error_chain_fmt(self, f)
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
tracing::error!("{:?}", self);
match &self {
AppError::UnexpectedError(_) => {
let template = MessageTemplate::Error {
message: "An internal server error occured.".into(),
};
Html(template.render().unwrap()).into_response()
}
AppError::ValidationError(error) => {
let template = MessageTemplate::Error {
message: error.to_string(),
};
Html(template.render().unwrap()).into_response()
}
AppError::NotAuthenticated => {
let mut headers = HeaderMap::new();
headers.insert("HX-Redirect", "/login".parse().unwrap());
(StatusCode::UNAUTHORIZED, headers).into_response()
}
}
}
}
impl From<AdminError> for AppError {
fn from(value: AdminError) -> Self {
match value {
AdminError::UnexpectedError(error) => AppError::UnexpectedError(error),
AdminError::NotAuthenticated => AppError::NotAuthenticated,
AdminError::ChangePassword(s) => AppError::ValidationError(anyhow::anyhow!(s)),
AdminError::Publish(e) => AppError::ValidationError(e),
AdminError::Idempotency(s) => AppError::UnexpectedError(anyhow::anyhow!(s)),
}
}
}
#[derive(Template)]
#[template(path = "../templates/404.html")]
struct NotFoundTemplate;