From 9fb4d3e561786f01352cbd14894d994ea537b5ec Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Wed, 18 Sep 2024 12:16:43 -0400 Subject: Return 404s when resources are not found. This is implemented by making the return values, in most cases, idiosyncratic ad-hoc types that then convert to the approprate error response. This also should make endpoints more testable, since the return values can now be inspected to check their properties without having to process or parse an HTTP response. --- src/index/routes.rs | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) (limited to 'src/index') diff --git a/src/index/routes.rs b/src/index/routes.rs index 32c7f12..37f6dc9 100644 --- a/src/index/routes.rs +++ b/src/index/routes.rs @@ -1,13 +1,13 @@ use axum::{ extract::{Path, State}, http::{header, StatusCode}, - response::IntoResponse, + response::{IntoResponse, Response}, routing::get, Router, }; use maud::Markup; -use super::templates; +use super::{app, templates}; use crate::{ app::App, error::InternalError, @@ -49,11 +49,31 @@ async fn channel( State(app): State, _: Login, Path(channel): Path, -) -> Result { - let channel = app.index().channel(&channel).await?; +) -> Result { + let channel = app + .index() + .channel(&channel) + .await + // impl From would work here, but it'd take more code. + .map_err(ChannelError)?; Ok(templates::channel(&channel)) } +#[derive(Debug)] +struct ChannelError(app::Error); + +impl IntoResponse for ChannelError { + fn into_response(self) -> Response { + let Self(error) = self; + match error { + not_found @ app::Error::ChannelNotFound(_) => { + (StatusCode::NOT_FOUND, not_found.to_string()).into_response() + } + app::Error::DatabaseError(error) => InternalError::from(error).into_response(), + } + } +} + pub fn router() -> Router { Router::new() .route("/", get(index)) -- cgit v1.2.3