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

@@ -4,19 +4,12 @@ mod logout;
mod newsletters;
mod posts;
use crate::{routes::error_chain_fmt, templates::MessageTemplate};
use askama::Template;
use axum::{
Json,
http::HeaderMap,
response::{Html, IntoResponse, Response},
};
use crate::routes::error_chain_fmt;
pub use change_password::*;
pub use dashboard::*;
pub use logout::*;
pub use newsletters::*;
pub use posts::*;
use reqwest::StatusCode;
#[derive(thiserror::Error)]
pub enum AdminError {
@@ -37,45 +30,3 @@ impl std::fmt::Debug for AdminError {
error_chain_fmt(self, f)
}
}
impl IntoResponse for AdminError {
fn into_response(self) -> Response {
#[derive(serde::Serialize)]
struct ErrorResponse<'a> {
message: &'a str,
}
tracing::error!("{:?}", self);
match &self {
AdminError::UnexpectedError(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "An internal server error occured.",
}),
)
.into_response(),
AdminError::NotAuthenticated => {
let mut headers = HeaderMap::new();
headers.insert("HX-Redirect", "/login".parse().unwrap());
headers.insert("Location", "/login".parse().unwrap());
(StatusCode::SEE_OTHER, headers).into_response()
}
AdminError::ChangePassword(e) => {
let template = MessageTemplate::Error {
message: e.to_owned(),
};
Html(template.render().unwrap()).into_response()
}
AdminError::Publish(e) => {
let template = MessageTemplate::Error {
message: e.to_string(),
};
Html(template.render().unwrap()).into_response()
}
AdminError::Idempotency(e) => {
(StatusCode::BAD_REQUEST, Json(ErrorResponse { message: e })).into_response()
}
}
}
}