http_error.rs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. use actix_web::{HttpResponse, ResponseError, http::StatusCode};
  2. use thiserror::Error;
  3. use serde::Serialize;
  4. #[derive(Serialize)]
  5. struct ErrorBody {
  6. error: ErrorInfo
  7. }
  8. #[derive(Serialize)]
  9. struct ErrorInfo {
  10. code: u16,
  11. message: String
  12. }
  13. #[derive(Error, Debug)]
  14. pub enum HttpError {
  15. #[error("{0}")]
  16. JsonDeserializationError(String),
  17. #[error("Internal Server Error")]
  18. Database(#[from] sqlx::Error),
  19. #[error("{0}")]
  20. InvalidInput(String),
  21. #[error("Internal Server Error")]
  22. InternalError(String),
  23. #[error("Unauthorized")]
  24. Auth,
  25. #[error("Invalid UUID")]
  26. InvalidUuid(#[from] uuid::Error),
  27. #[error("Unauthorized")]
  28. InvalidJwt(#[from] jsonwebtoken::errors::Error),
  29. #[error("{0}")]
  30. NotFound(String)
  31. }
  32. impl ResponseError for HttpError {
  33. fn status_code(&self) -> StatusCode {
  34. match self {
  35. HttpError::JsonDeserializationError(_) => StatusCode::BAD_REQUEST,
  36. HttpError::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,
  37. HttpError::InvalidInput(_) => StatusCode::BAD_REQUEST,
  38. HttpError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
  39. HttpError::Auth => StatusCode::UNAUTHORIZED,
  40. HttpError::InvalidUuid(_) => StatusCode::BAD_REQUEST,
  41. HttpError::InvalidJwt(_) => StatusCode::UNAUTHORIZED,
  42. HttpError::NotFound(_) => StatusCode::NOT_FOUND
  43. }
  44. }
  45. fn error_response(&self) -> HttpResponse {
  46. match self {
  47. HttpError::Database(s) => {eprintln!("Database error: {}", s)},
  48. HttpError::InternalError(s) => {eprintln!("Internal Error: {}", s)}
  49. _ => ()
  50. };
  51. let body = ErrorBody {
  52. error: ErrorInfo {
  53. code: self.status_code().as_u16(),
  54. message: self.to_string()
  55. }
  56. };
  57. HttpResponse::build(self.status_code()).json(body)
  58. }
  59. }