From 5e7e4c658e2048882fc008889a455aaf88fbf156 Mon Sep 17 00:00:00 2001 From: Paul van Tilburg Date: Sun, 9 Jun 2019 18:16:55 +0200 Subject: [PATCH] Add error catchers --- src/catchers.rs | 23 +++++++++++++++++++++++ src/main.rs | 7 ++++++- 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 src/catchers.rs diff --git a/src/catchers.rs b/src/catchers.rs new file mode 100644 index 0000000..ebdfc60 --- /dev/null +++ b/src/catchers.rs @@ -0,0 +1,23 @@ +//! The application error catchers + +use rocket::catch; +use rocket_contrib::json; +use rocket_contrib::json::JsonValue; + +/// Catches an HTTP 404 (Not Found) error. +#[catch(404)] +pub fn not_found() -> JsonValue { + json!({ + "status": "error", + "reason": "Resource was not found", + }) +} + +/// Catches an HTTP 422 (Unprocessable Entity) error. +#[catch(422)] +pub fn unprocessable_entity() -> JsonValue { + json!({ + "status": "error", + "reason": "Could not parse JSON body or fields were missing", + }) +} diff --git a/src/main.rs b/src/main.rs index d1b9d22..7b98f2f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,9 +4,10 @@ #[macro_use] extern crate diesel; -use rocket::{routes, Rocket}; +use rocket::{catchers, routes, Rocket}; use rocket_contrib::serve::StaticFiles; +pub mod catchers; pub mod handlers; fn rocket() -> Rocket { @@ -52,6 +53,10 @@ fn rocket() -> Rocket { handlers::timeline::destroy, ], ) + .register(catchers![ + catchers::not_found, + catchers::unprocessable_entity + ]) } fn main() {