utils: Implement error struct

- Implement Responder trait for Error
- Implement Responder trait for Success

Signed-off-by: supercmmetry <vishaals2000@gmail.com>
This commit is contained in:
supercmmetry 2020-06-24 13:55:28 +05:30
parent da21eb1189
commit 74aa1e3852
No known key found for this signature in database
GPG Key ID: 8E60EF28A328E40D
5 changed files with 972 additions and 16 deletions

834
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -12,4 +12,10 @@ rocket_contrib = {version="0.4.4", default-features=false, features=["json"]}
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
serde_derive = "1.0" serde_derive = "1.0"
diesel = {version = "1.4.4", features = ["postgres", "r2d2", "chrono"]}
diesel_migrations = "1.4.0"
dotenv = "0.15.0" dotenv = "0.15.0"
jsonwebtoken = "7.1.2"
slog = "2.5.2"
slog-term = "2.6.0"
slog-async = "2.5.0"

View File

@ -2,16 +2,35 @@
#[macro_use] #[macro_use]
extern crate rocket; extern crate rocket;
#[macro_use]
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde;
#[macro_use]
extern crate slog;
pub mod api; pub mod api;
pub mod core; pub mod core;
pub mod utils;
use slog_term;
use slog_async;
use slog::Drain;
fn main() { fn main() {
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let logger = slog::Logger::root(drain, o!());
let mut rocket = rocket::ignite(); let mut rocket = rocket::ignite();
rocket = api::routes::fuel(rocket); rocket = api::routes::fuel(rocket);
rocket.launch(); rocket.manage(logger)
.launch();
} }

126
src/utils/errors.rs Normal file
View File

@ -0,0 +1,126 @@
use rocket::{http::{Status, ContentType}, response::Responder, Request, response, Response, Outcome, State};
use std::io::Cursor;
use slog::Logger;
use slog;
#[derive(Debug, Serialize, Clone)]
pub enum ErrorCode {
InvalidCredentials,
MultipleAuthToken,
NoAuthToken,
AuthTokenCreationFailed,
MalformedAuthToken,
ResourceNotFound,
ResourceAlreadyExists,
DatabaseError,
InvalidData,
NotAuthorized,
CorruptResource,
LogicalConflict,
Unknown,
}
#[derive(Debug, Serialize, Clone)]
pub struct Error {
code: ErrorCode,
msg: String,
}
impl Error {
pub fn new(code: ErrorCode) -> Error {
Error {
code,
msg: "".to_string(),
}.set_msg()
}
pub fn custom(code: ErrorCode, msg: String) -> Error {
Error {
code,
msg,
}
}
fn get_status_code(&self) -> Status {
match self.code {
ErrorCode::InvalidCredentials => Status::Forbidden,
ErrorCode::ResourceNotFound => Status::NotFound,
ErrorCode::MultipleAuthToken => Status::Conflict,
ErrorCode::NoAuthToken => Status::Forbidden,
ErrorCode::AuthTokenCreationFailed => Status::InternalServerError,
ErrorCode::MalformedAuthToken => Status::Forbidden,
ErrorCode::ResourceAlreadyExists => Status::Conflict,
ErrorCode::DatabaseError => Status::InternalServerError,
ErrorCode::InvalidData => Status::BadRequest,
ErrorCode::NotAuthorized => Status::Forbidden,
ErrorCode::CorruptResource => Status::InternalServerError,
ErrorCode::LogicalConflict => Status::BadRequest,
ErrorCode::Unknown => Status::InternalServerError
}
}
fn set_msg(mut self) -> Self {
self.msg = match self.code.clone() {
ErrorCode::InvalidCredentials => "invalid credentials were provided".to_string(),
ErrorCode::MultipleAuthToken => "multiple authorization tokens were provided".to_string(),
ErrorCode::NoAuthToken => "no authorization token was found".to_string(),
ErrorCode::AuthTokenCreationFailed => "authorization token creation failed".to_string(),
ErrorCode::MalformedAuthToken => "authorization token was malformed".to_string(),
ErrorCode::ResourceNotFound => "resource not found".to_string(),
ErrorCode::ResourceAlreadyExists => "the given resource already exists".to_string(),
ErrorCode::DatabaseError => "database error occured".to_string(),
ErrorCode::InvalidData => "invalid data provided".to_string(),
ErrorCode::NotAuthorized => "you are not authorized to perform the requested operation".to_string(),
ErrorCode::CorruptResource => "requested resource was corrupted".to_string(),
ErrorCode::LogicalConflict => "the request logically conflicts with the existing data".to_string(),
ErrorCode::Unknown => "unknown error occured".to_string()
};
self
}
}
impl<'r> Responder<'r> for Error {
fn respond_to(self, request: &Request) -> response::Result<'r> {
let logger = request.guard::<State<Logger>>();
if let Outcome::Success(logger) = logger {
error!(logger, "{}", serde_json::to_string(&self).unwrap());
}
Response::build()
.status(self.get_status_code())
.header(ContentType::JSON)
.sized_body(Cursor::new(serde_json::to_string(&self).unwrap()))
.ok()
}
}
#[derive(Serialize)]
pub struct Success {
msg: String
}
impl Success {
pub fn new(msg: &str) -> Success {
Success {
msg: msg.to_string()
}
}
}
impl<'r> Responder<'r> for Success {
fn respond_to(self, request: &Request) -> response::Result<'r> {
let logger = request.guard::<State<Logger>>();
if let Outcome::Success(logger) = logger {
info!(logger, "{}", serde_json::to_string(&self).unwrap());
}
Response::build()
.status(Status::Ok)
.header(ContentType::JSON)
.sized_body(Cursor::new(serde_json::to_string(&self).unwrap()))
.ok()
}
}

1
src/utils/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod errors;