http_error.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. }
  24. impl ResponseError for HttpError {
  25. fn status_code(&self) -> StatusCode {
  26. match self {
  27. HttpError::JsonDeserializationError(_) => StatusCode::BAD_REQUEST,
  28. HttpError::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,
  29. HttpError::InvalidInput(_) => StatusCode::BAD_REQUEST,
  30. HttpError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR
  31. }
  32. }
  33. fn error_response(&self) -> HttpResponse {
  34. match self {
  35. HttpError::Database(s) => {eprintln!("Database error: {}", s)},
  36. HttpError::InternalError(s) => {eprintln!("Internal Error: {}", s)}
  37. _ => ()
  38. };
  39. let body = ErrorBody {
  40. error: ErrorInfo {
  41. code: self.status_code().as_u16(),
  42. message: self.to_string()
  43. }
  44. };
  45. HttpResponse::build(self.status_code()).json(body)
  46. }
  47. }