app_error.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use actix_web::{HttpResponse, ResponseError, http::StatusCode};
  2. use thiserror::Error;
  3. use serde::Serialize;
  4. #[derive(Debug, Serialize)]
  5. struct ErrorBody {
  6. error: ErrorInfo
  7. }
  8. #[derive(Debug, Serialize)]
  9. struct ErrorInfo {
  10. code: u16,
  11. message: String
  12. }
  13. #[derive(Debug, Error)]
  14. pub enum AppError {
  15. #[error("Database error")]
  16. Database(#[from] mongodb::error::Error),
  17. #[error("Invalid ID")]
  18. InvalidID(#[from] bson::oid::Error),
  19. #[error("{0}")]
  20. InvalidInput(String),
  21. #[error("{0}")]
  22. InternalError(String),
  23. #[error("Unauthorized")]
  24. Auth
  25. }
  26. impl ResponseError for AppError {
  27. fn status_code(&self) -> StatusCode {
  28. match self {
  29. AppError::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,
  30. AppError::InvalidID(_) => StatusCode::BAD_REQUEST,
  31. AppError::InvalidInput(_) => StatusCode::BAD_REQUEST,
  32. AppError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,
  33. AppError::Auth => StatusCode::UNAUTHORIZED
  34. }
  35. }
  36. fn error_response(&self) -> HttpResponse {
  37. let body = ErrorBody {
  38. error: ErrorInfo {
  39. code: self.status_code().as_u16(),
  40. message: self.to_string()
  41. }
  42. };
  43. HttpResponse::build(self.status_code()).json(body)
  44. }
  45. }
  46. impl AppError {
  47. pub fn invalid_input(msg: &str) -> Self {
  48. AppError::InvalidInput(msg.to_owned())
  49. }
  50. pub fn internal_error(msg: &str) -> Self {
  51. AppError::InternalError(msg.to_owned())
  52. }
  53. }