| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- 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),
- #[error("Unauthorized")]
- Auth,
- #[error("Invalid UUID")]
- InvalidUuid(#[from] uuid::Error),
- #[error("Unauthorized")]
- InvalidJwt(#[from] jsonwebtoken::errors::Error),
- #[error("{0}")]
- NotFound(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,
- HttpError::Auth => StatusCode::UNAUTHORIZED,
- HttpError::InvalidUuid(_) => StatusCode::BAD_REQUEST,
- HttpError::InvalidJwt(_) => StatusCode::UNAUTHORIZED,
- HttpError::NotFound(_) => StatusCode::NOT_FOUND
- }
- }
- 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)
- }
- }
|