| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- use actix_web::{HttpResponse, ResponseError, http::StatusCode};
- use thiserror::Error;
- use serde::Serialize;
- #[derive(Serialize)]
- struct ErrorBody {
- error: ErrorInfo
- }
- #[derive(Serialize)]
- struct ErrorInfo {
- code: u16,
- message: String
- }
- #[derive(Error, Debug)]
- pub enum HttpError {
- #[error("{0}")]
- JsonDeserializationError(String),
- #[error("Internal Server Error")]
- Database(#[from] sqlx::Error),
- #[error("{0}")]
- InvalidInput(String),
- #[error("Internal Server Error")]
- InternalError(String)
- }
- impl ResponseError for HttpError {
- fn status_code(&self) -> StatusCode {
- match self {
- HttpError::JsonDeserializationError(_) => StatusCode::BAD_REQUEST,
- HttpError::Database(_) => StatusCode::INTERNAL_SERVER_ERROR,
- HttpError::InvalidInput(_) => StatusCode::BAD_REQUEST,
- HttpError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR
- }
- }
- fn error_response(&self) -> HttpResponse {
- match self {
- HttpError::Database(s) => {eprintln!("Database error: {}", s)},
- HttpError::InternalError(s) => {eprintln!("Internal Error: {}", s)}
- _ => ()
- };
- let body = ErrorBody {
- error: ErrorInfo {
- code: self.status_code().as_u16(),
- message: self.to_string()
- }
- };
- HttpResponse::build(self.status_code()).json(body)
- }
- }
|