feat: add error handling

This commit is contained in:
Alexander Navarro 2025-02-13 15:45:06 -03:00
parent 6bf3947df3
commit 8d8388e81a
5 changed files with 77 additions and 9 deletions

39
src/error.rs Normal file
View file

@ -0,0 +1,39 @@
use axum::response::Html;
use axum::{http::StatusCode, response::IntoResponse};
pub type Result<T> = std::result::Result<T, Error>;
pub type ResultTemplate = std::result::Result<Html<String>, Error>;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Unhandled error: {0}")]
Generic(String),
#[error("Unhandled error: {0}")]
Static(&'static str),
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
Template(#[from] minijinja::Error),
#[error("Error in runtime execution: {0}")]
Runtime(&'static str),
// #[error(transparent)]
// DatabaseOperation(#[from] sqlx::Error),
}
impl IntoResponse for Error {
fn into_response(self) -> axum::response::Response {
let (status, message) = match self {
_ => (
StatusCode::INTERNAL_SERVER_ERROR,
"An unexpected error has ocurred!",
),
};
(status, message).into_response()
}
}

3
src/lib.rs Normal file
View file

@ -0,0 +1,3 @@
mod error;
pub use error::{Error, Result, ResultTemplate};

View file

@ -1,3 +1,6 @@
#![allow(unused)]
#![allow(dead_code)]
use std::sync::Arc;
use axum::extract::State;
@ -5,6 +8,7 @@ use axum::http::StatusCode;
use axum::response::Html;
use axum::routing::get;
use axum::Router;
use compendium::{Result, ResultTemplate};
use minijinja::{context, Environment};
struct AppState {
@ -12,11 +16,9 @@ struct AppState {
}
#[tokio::main]
async fn main() {
async fn main() -> Result<()> {
let mut tmpl_env = Environment::new();
tmpl_env
.add_template("base", include_str!("../templates/base.html"))
.unwrap();
tmpl_env.add_template("base", include_str!("../templates/base.html"))?;
let app_state = Arc::new(AppState { tmpl_env });
@ -28,14 +30,16 @@ async fn main() {
#[cfg(debug_assertions)]
let app = app.layer(tower_livereload::LiveReloadLayer::new());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app).await?;
Ok(())
}
async fn handler_home(State(state): State<Arc<AppState>>) -> Result<Html<String>, StatusCode> {
let template = state.tmpl_env.get_template("base").unwrap();
async fn handler_home(State(state): State<Arc<AppState>>) -> ResultTemplate {
let template = state.tmpl_env.get_template("base")?;
let content = template.render(context!()).unwrap();
let content = template.render(context!())?;
Ok(Html(content))
}