From 23e4f52284ad5fa0b068220c54a255ff9fa7b18f Mon Sep 17 00:00:00 2001 From: Yigit Sever Date: Tue, 13 Apr 2021 20:37:54 +0300 Subject: Add verbose error messages Not happy with the solution one bit but using error.rs at https://blog.logrocket.com/create-an-async-crud-web-service-in-rust-with-warp/ was not working Basically we just handcraft every single response on the spot, there is some repetition and it's ugly but need to move on --- src/error.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/error.rs (limited to 'src/error.rs') diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..7339a06 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,38 @@ +use log::warn; +use serde::Serialize; +use std::convert::Infallible; +use warp::{http::StatusCode, Rejection, Reply}; + +#[derive(Serialize)] +struct ErrorResponse { + message: String, +} + +pub async fn handle_rejection(err: Rejection) -> std::result::Result { + let code; + let message; + + if err.is_not_found() { + code = StatusCode::NOT_FOUND; + message = "Requested resource is not found"; + } else if let Some(_) = err.find::() { + code = StatusCode::BAD_REQUEST; + message = "Error: JSON body is not formatted correctly, check your payload"; + } else if let Some(_) = err.find::() { + code = StatusCode::METHOD_NOT_ALLOWED; + message = "Error: Authorization header missing, cannot authorize"; + } else if let Some(_) = err.find::() { + code = StatusCode::METHOD_NOT_ALLOWED; + message = "Error: method not allowed on this endpoint"; + } else { + warn!("unhandled error: {:?}", err); + code = StatusCode::INTERNAL_SERVER_ERROR; + message = "Internal Server Error"; + } + + let json = warp::reply::json(&ErrorResponse { + message: message.to_owned(), + }); + + Ok(warp::reply::with_status(json, code)) +} -- cgit v1.2.3-70-g09d2