From 3ec1485ae7856e76db8eb2f305ef5950e60f7d8c Mon Sep 17 00:00:00 2001 From: Cara Salter Date: Mon, 30 May 2022 00:01:39 -0400 Subject: errors/handlers: Make 404 errors more clear Instead of returning a 500 for every error, this should make it a little easier to return specific status codes for different errors --- src/handlers/ships.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) (limited to 'src/handlers') diff --git a/src/handlers/ships.rs b/src/handlers/ships.rs index ddb81a6..75f5dc5 100644 --- a/src/handlers/ships.rs +++ b/src/handlers/ships.rs @@ -1,10 +1,11 @@ use std::sync::Arc; use axum::{Json, extract::Path, Extension}; +use hyper::StatusCode; use solarlib::ship::{Ship, DbShip, Sha256}; -use sqlx::{query_as, query}; +use sqlx::{query_as, query, Error as SqlxError}; -use crate::{errors::{JsonResult, StringResult}, State}; +use crate::{errors::{JsonResult, StringResult, ServiceError}, State}; pub async fn list(state: Extension>) -> JsonResult>> { @@ -38,7 +39,19 @@ pub async fn delete(Path(shasum): Path, state: Extension>) -> pub async fn get(Path(shasum): Path, state: Extension>) -> JsonResult> { let mut conn = state.conn.acquire().await?; - let db_ship = query_as!(DbShip, "SELECT * FROM ships WHERE shasum=$1", shasum.to_string()).fetch_one(&mut conn).await?; + let db_ship = match query_as!(DbShip, "SELECT * FROM ships WHERE shasum=$1", shasum.to_string()).fetch_one(&mut conn).await { + Ok(d) => d, + Err(e) => { + match e { + SqlxError::RowNotFound => { + return Err(ServiceError::NotFound) + }, + _ => { + return Err(e.into()); + } + } + }, + }; Ok(Json(db_ship)) } -- cgit v1.2.3