From 0de8fb33da89ffdc66d84d4d7a59b15f96a6c4ea Mon Sep 17 00:00:00 2001 From: supercmmetry Date: Fri, 26 Jun 2020 08:38:32 +0530 Subject: [PATCH] api: Add catchers - Added catchers for 404, 422 and 500 Signed-off-by: supercmmetry --- src/api/catchers/mod.rs | 34 ++++++++++++++++++++++++++++++++++ src/main.rs | 1 + 2 files changed, 35 insertions(+) diff --git a/src/api/catchers/mod.rs b/src/api/catchers/mod.rs index e69de29..ca6e3a4 100644 --- a/src/api/catchers/mod.rs +++ b/src/api/catchers/mod.rs @@ -0,0 +1,34 @@ +use rocket::Rocket; +use rocket::response::status; +use rocket::http::Status; +use rocket_contrib::json::Json; +use serde_json::Value; + +#[catch(404)] +fn not_found() -> status::Custom> { + status::Custom(Status::NotFound, Json(json!({ + "err":"route not found", + "msg": "The given route does not exist" + }))) +} + +#[catch(422)] +fn unprocessable_entity() -> status::Custom> { + status::Custom(Status::UnprocessableEntity, Json(json!({ + "err":"failed to process entity", + "msg": "The given object could not be processed. This could be due to sending \ + malformed or incomplete JSON objects in the request body." + }))) +} + +#[catch(500)] +fn internal_server_error() -> status::Custom> { + status::Custom(Status::NotFound, Json(json!({ + "err":"internal server error", + "msg": "Something went wrong, try again" + }))) +} + +pub fn fuel(rocket: Rocket) -> Rocket { + rocket.register(catchers![not_found, unprocessable_entity, internal_server_error]) +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index cbf54e2..220a5a8 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,6 +46,7 @@ fn main() { let mut rocket = rocket::ignite(); rocket = api::routes::fuel(rocket); + rocket = api::catchers::fuel(rocket); rocket.manage(utils::db::pool()) .manage(logger)