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/channel/routes.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) (limited to 'src/channel/routes.rs') diff --git a/src/channel/routes.rs b/src/channel/routes.rs index 1379153..847e0b4 100644 --- a/src/channel/routes.rs +++ b/src/channel/routes.rs @@ -1,10 +1,12 @@ use axum::{ extract::{Form, Path, State}, - response::{IntoResponse, Redirect}, + http::StatusCode, + response::{IntoResponse, Redirect, Response}, routing::post, Router, }; +use super::app::EventsError; use crate::{ app::App, clock::RequestedAt, @@ -44,10 +46,26 @@ async fn on_send( State(app): State, login: Login, Form(form): Form, -) -> Result { +) -> Result { app.channels() .send(&login, &channel, &form.message, &sent_at) - .await?; + .await + // Could impl `From` here, but it's more code and this is used once. + .map_err(ErrorResponse)?; Ok(Redirect::to(&format!("/{}", channel))) } + +struct ErrorResponse(EventsError); + +impl IntoResponse for ErrorResponse { + fn into_response(self) -> Response { + let Self(error) = self; + match error { + not_found @ EventsError::ChannelNotFound(_) => { + (StatusCode::NOT_FOUND, not_found.to_string()).into_response() + } + EventsError::DatabaseError(error) => InternalError::from(error).into_response(), + } + } +} -- cgit v1.2.3