Improve server error handling

This commit is contained in:
Joscha 2024-03-10 15:26:50 +01:00
parent 9d17d34642
commit e0a668a581
6 changed files with 79 additions and 33 deletions

View file

@ -0,0 +1,39 @@
use std::{error, fmt, result};
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
use super::statuscode::status_code_with_info;
pub struct Error(pub anyhow::Error);
impl<E> From<E> for Error
where
E: error::Error + Send + Sync + 'static,
{
fn from(value: E) -> Self {
Self(anyhow::Error::from(value))
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
impl IntoResponse for Error {
fn into_response(self) -> Response {
status_code_with_info(StatusCode::INTERNAL_SERVER_ERROR, &self.0)
}
}
pub type Result<T> = result::Result<T, Error>;

View file

@ -4,16 +4,14 @@ use axum::{
};
use rust_embed::RustEmbed;
use super::statuscode::status_code;
#[derive(RustEmbed)]
#[folder = "static"]
struct StaticFiles;
struct StaticFile(String);
fn not_found() -> Response {
(StatusCode::NOT_FOUND, "404 Not Found").into_response()
}
fn look_up_path(path: &str) -> Option<Response> {
let path = path.trim_start_matches('/');
let file = StaticFiles::get(path)?;
@ -32,13 +30,13 @@ impl IntoResponse for StaticFile {
if path.ends_with(".html") {
// A file `/foo/bar.html` should not be accessible directly, only
// indirectly at `/foo/bar`.
return not_found();
return status_code(StatusCode::NOT_FOUND);
}
if path.ends_with("/index") {
// A file `/foo/index.html` should not be accessible directly, only
// indirectly at `/foo/`.
return not_found();
return status_code(StatusCode::NOT_FOUND);
}
if path.ends_with('/') {
@ -55,7 +53,7 @@ impl IntoResponse for StaticFile {
return response;
}
not_found()
status_code(StatusCode::NOT_FOUND)
}
}

View file

@ -0,0 +1,15 @@
use core::fmt;
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
pub fn status_code(code: StatusCode) -> Response {
(code, code.to_string()).into_response()
}
pub fn status_code_with_info<I: fmt::Display>(code: StatusCode, info: &I) -> Response {
let message = format!("{code}\n\n{info}");
(code, message).into_response()
}