Switch to ApiResponse struct instead of ErrorModel

This commit is contained in:
Rohan Sircar 2021-05-12 21:05:15 +05:30
parent 1d74b75ca8
commit 4673818894
6 changed files with 52 additions and 68 deletions

View File

@ -3,7 +3,7 @@ use bcrypt::BcryptError;
use custom_error::custom_error; use custom_error::custom_error;
// use derive_more::Display; // use derive_more::Display;
// use diesel::result::DatabaseErrorKind; // use diesel::result::DatabaseErrorKind;
use crate::models::errors::*; use crate::models::api_response::*;
use std::convert::From; use std::convert::From;
// impl From<DBError> for DomainError { // impl From<DBError> for DomainError {
@ -37,57 +37,36 @@ impl ResponseError for DomainError {
let err = self; let err = self;
match self { match self {
DomainError::PwdHashError { source: _ } => { DomainError::PwdHashError { source: _ } => {
HttpResponse::InternalServerError().json(ErrorModel { HttpResponse::InternalServerError()
// error_code: 500, .json(ApiResponse::failure(err.to_string()))
success: false,
reason: err.to_string(),
})
} }
DomainError::DbError { source: _ } => { DomainError::DbError { source: _ } => {
tracing::error!("{}", err); tracing::error!("{}", err);
HttpResponse::InternalServerError().json(ErrorModel { HttpResponse::InternalServerError()
// error_code: 500, .json(ApiResponse::failure("Error in database".to_owned()))
success: false,
reason: "Error in database".to_owned(),
})
} }
DomainError::DbPoolError { source: _ } => { DomainError::DbPoolError { source: _ } => {
tracing::error!("{}", err); tracing::error!("{}", err);
HttpResponse::InternalServerError().json(ErrorModel { HttpResponse::InternalServerError().json(ApiResponse::failure(
// error_code: 500, "Error getting database pool".to_owned(),
success: false, ))
reason: "Error getting database pool".to_owned(),
})
} }
DomainError::PasswordError { cause: _ } => { DomainError::PasswordError { cause: _ } => {
HttpResponse::BadRequest().json(ErrorModel { HttpResponse::BadRequest()
// error_code: 400, .json(ApiResponse::failure(err.to_string()))
success: false,
reason: err.to_string(),
})
} }
DomainError::EntityDoesNotExistError { message: _ } => { DomainError::EntityDoesNotExistError { message: _ } => {
HttpResponse::NotFound().json(ErrorModel { HttpResponse::NotFound()
// error_code: 400, .json(ApiResponse::failure(err.to_string()))
success: false,
reason: err.to_string(),
})
} }
DomainError::ThreadPoolError { message: _ } => { DomainError::ThreadPoolError { message: _ } => {
tracing::error!("{}", err); tracing::error!("{}", err);
HttpResponse::InternalServerError().json(ErrorModel { HttpResponse::InternalServerError().json(ApiResponse::failure(
// error_code: 400, "Thread pool error occurred".to_owned(),
success: false, ))
reason: "Thread pool error occurred".to_owned(),
})
}
DomainError::AuthError { message: _ } => {
HttpResponse::Forbidden().json(ErrorModel {
// error_code: 400,
success: false,
reason: err.to_string(),
})
} }
DomainError::AuthError { message: _ } => HttpResponse::Forbidden()
.json(ApiResponse::failure(err.to_string())),
} }
} }
} }

View File

@ -1,4 +1,4 @@
pub mod users; pub mod users;
pub use self::users::*; pub use self::users::*;
pub mod errors; pub mod api_response;
pub use self::errors::*; pub use self::api_response::*;

View File

@ -0,0 +1,22 @@
use serde::{Deserialize, Serialize};
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, new)]
pub struct ApiResponse<T> {
success: bool,
response: T,
}
impl<T> ApiResponse<T> {
pub fn success(&self) -> bool {
self.success
}
pub fn response(&self) -> &T {
&self.response
}
pub fn successful(response: T) -> ApiResponse<T> {
ApiResponse::new(true, response)
}
pub fn failure(response: T) -> ApiResponse<T> {
ApiResponse::new(false, response)
}
}

View File

@ -1,14 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, new)]
pub struct JsonErrorModel<'a> {
status_code: i16,
pub line: String,
pub reason: &'a str,
}
#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, new)]
pub struct ErrorModel {
// pub error_code: i16,
pub success: bool,
pub reason: String,
}

View File

@ -1,4 +1,4 @@
use actix_web::{get, post, web, HttpResponse}; use actix_web::{get, web, HttpResponse};
use crate::services::UserService; use crate::services::UserService;
use crate::{actions, models}; use crate::{actions, models};
@ -120,7 +120,7 @@ pub async fn add_user(
// cause: e.to_string(), // cause: e.to_string(),
// }; // };
// Err(res2) // Err(res2)
let res = HttpResponse::BadRequest().body(e.to_string()); let res = HttpResponse::BadRequest().json(e);
// .json(models::ErrorModel::new( // .json(models::ErrorModel::new(
// 40, // 40,
// "Error registering user due to validation errors", // "Error registering user due to validation errors",

View File

@ -3,7 +3,7 @@ use crate::common;
mod tests { mod tests {
use super::*; use super::*;
use actix_demo::models::ErrorModel; use actix_demo::models::ApiResponse;
use actix_web::dev::Service as _; use actix_web::dev::Service as _;
use actix_web::http::StatusCode; use actix_web::http::StatusCode;
use actix_web::test; use actix_web::test;
@ -13,14 +13,13 @@ mod tests {
let req = test::TestRequest::get().uri("/api/users").to_request(); let req = test::TestRequest::get().uri("/api/users").to_request();
let resp = common::test_app().await.unwrap().call(req).await.unwrap(); let resp = common::test_app().await.unwrap().call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let body: ErrorModel = test::read_body_json(resp).await; let body: ApiResponse<String> = test::read_body_json(resp).await;
tracing::debug!("{:?}", body); tracing::debug!("{:?}", body);
assert_eq!( assert_eq!(
body, body,
ErrorModel { ApiResponse::failure(
success: false, "Entity does not exist - No users available".to_owned()
reason: "Entity does not exist - No users available".to_owned() )
}
); );
} }
@ -30,15 +29,13 @@ mod tests {
let req = test::TestRequest::get().uri("/api/users/1").to_request(); let req = test::TestRequest::get().uri("/api/users/1").to_request();
let resp = common::test_app().await.unwrap().call(req).await.unwrap(); let resp = common::test_app().await.unwrap().call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let body: ErrorModel = test::read_body_json(resp).await; let body: ApiResponse<String> = test::read_body_json(resp).await;
tracing::debug!("{:?}", body); tracing::debug!("{:?}", body);
assert_eq!( assert_eq!(
body, body,
ErrorModel { ApiResponse::failure(
success: false, "Entity does not exist - No user found with uid: 1".to_owned()
reason: "Entity does not exist - No user found with uid: 1" )
.to_owned()
}
); );
} }
} }