Explorar o código

Create the base of the app error module.

Lee Morgan hai 2 meses
pai
achega
a2eb9e8603
Modificáronse 3 ficheiros con 47 adicións e 0 borrados
  1. 2 0
      Cargo.lock
  2. 2 0
      Cargo.toml
  3. 43 0
      src/app_error.rs

+ 2 - 0
Cargo.lock

@@ -863,7 +863,9 @@ name = "homo"
 version = "0.1.0"
 dependencies = [
  "actix-web",
+ "serde",
  "sqlx",
+ "thiserror",
 ]
 
 [[package]]

+ 2 - 0
Cargo.toml

@@ -5,4 +5,6 @@ edition = "2024"
 
 [dependencies]
 actix-web = "4.13.0"
+serde = "1.0.228"
 sqlx = "0.8.6"
+thiserror = "2.0.18"

+ 43 - 0
src/app_error.rs

@@ -0,0 +1,43 @@
+use actix_web::{HttpResponse, ResponseError, http::StatusCode};
+use thiserror::ErrorInfo;
+use serde::Serialize;
+
+#[derive(Serialize)]
+struct ErrorBody {
+    error: ErrorInfo
+}
+
+#[derive(Serialize)]
+struct ErrorInfo {
+    code: u16,
+    message: String
+}
+
+#[derive(Error)]
+pub enum AppError {
+    #[error("Internal Server Error")]
+    InternalError(String)
+}
+
+impl ResponseError for AppError {
+    fn status_code(&self) -> StatusCode {
+        match self {
+            AppError::InternalError => StatusCode::INTERNAL_SERVER_ERROR
+        }
+    }
+
+    fn error_response(&self) -> HttpResponse {
+        match self {
+            AppError::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)
+    }
+}