diff options
Diffstat (limited to 'src/error.rs')
| -rw-r--r-- | src/error.rs | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..0db26c4 --- /dev/null +++ b/src/error.rs | |||
| @@ -0,0 +1,63 @@ | |||
| 1 | use serde::Serialize; | ||
| 2 | use std::convert::Infallible; | ||
| 3 | use thiserror::Error; | ||
| 4 | use warp::{http::StatusCode, Rejection, Reply}; | ||
| 5 | |||
| 6 | #[derive(Error, Debug)] | ||
| 7 | pub enum Error { | ||
| 8 | // #[error("wrong credentials")] | ||
| 9 | // WrongCredentialsError, | ||
| 10 | #[error("jwt token not valid")] | ||
| 11 | JWTTokenError, | ||
| 12 | // #[error("jwt token creation error")] | ||
| 13 | // JWTTokenCreationError, | ||
| 14 | #[error("no auth header")] | ||
| 15 | NoAuthHeaderError, | ||
| 16 | #[error("invalid auth header")] | ||
| 17 | InvalidAuthHeaderError, | ||
| 18 | // #[error("no permission")] | ||
| 19 | // NoPermissionError, | ||
| 20 | } | ||
| 21 | |||
| 22 | #[derive(Serialize, Debug)] | ||
| 23 | struct ErrorResponse { | ||
| 24 | message: String, | ||
| 25 | status: String, | ||
| 26 | } | ||
| 27 | |||
| 28 | impl warp::reject::Reject for Error {} | ||
| 29 | |||
| 30 | pub async fn handle_rejection(err: Rejection) -> std::result::Result<impl Reply, Infallible> { | ||
| 31 | let (code, message) = if err.is_not_found() { | ||
| 32 | (StatusCode::NOT_FOUND, "Not Found".to_string()) | ||
| 33 | } else if let Some(e) = err.find::<Error>() { | ||
| 34 | match e { | ||
| 35 | // Error::WrongCredentialsError => (StatusCode::FORBIDDEN, e.to_string()), | ||
| 36 | // Error::NoPermissionError => (StatusCode::UNAUTHORIZED, e.to_string()), | ||
| 37 | Error::JWTTokenError => (StatusCode::UNAUTHORIZED, e.to_string()), | ||
| 38 | // Error::JWTTokenCreationError => ( | ||
| 39 | // StatusCode::INTERNAL_SERVER_ERROR, | ||
| 40 | // "Internal Server Error".to_string(), | ||
| 41 | // ), | ||
| 42 | _ => (StatusCode::BAD_REQUEST, e.to_string()), | ||
| 43 | } | ||
| 44 | } else if err.find::<warp::reject::MethodNotAllowed>().is_some() { | ||
| 45 | ( | ||
| 46 | StatusCode::METHOD_NOT_ALLOWED, | ||
| 47 | "Method Not Allowed".to_string(), | ||
| 48 | ) | ||
| 49 | } else { | ||
| 50 | eprintln!("unhandled error: {:?}", err); | ||
| 51 | ( | ||
| 52 | StatusCode::INTERNAL_SERVER_ERROR, | ||
| 53 | "Internal Server Error".to_string(), | ||
| 54 | ) | ||
| 55 | }; | ||
| 56 | |||
| 57 | let json = warp::reply::json(&ErrorResponse { | ||
| 58 | status: code.to_string(), | ||
| 59 | message, | ||
| 60 | }); | ||
| 61 | |||
| 62 | Ok(warp::reply::with_status(json, code)) | ||
| 63 | } | ||
