Add delete handler and json-payload error response
This commit is contained in:
parent
e6278176e4
commit
7254eddc6c
8 changed files with 162 additions and 51 deletions
src/db
|
@ -1,17 +1,22 @@
|
|||
use actix_web::HttpResponse;
|
||||
use actix_web::http::StatusCode;
|
||||
use serde::ser::SerializeStruct;
|
||||
use serde::{Serialize, Serializer};
|
||||
|
||||
pub enum DatabaseError {
|
||||
DeleteError,
|
||||
InsertError,
|
||||
InsertGetError,
|
||||
NotFound,
|
||||
Protected
|
||||
}
|
||||
|
||||
impl DatabaseError {
|
||||
fn to_code(&self) -> u32 {
|
||||
fn get_code(&self) -> StatusCode {
|
||||
match self {
|
||||
DatabaseError::NotFound => 404,
|
||||
_ => 500
|
||||
DatabaseError::NotFound => StatusCode::NOT_FOUND,
|
||||
DatabaseError::Protected => StatusCode::FORBIDDEN,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -23,7 +28,7 @@ impl Serialize for DatabaseError {
|
|||
{
|
||||
let mut s = serializer.serialize_struct("error", 3)?;
|
||||
s.serialize_field("type", "database-error")?;
|
||||
s.serialize_field("code", &self.to_code())?;
|
||||
s.serialize_field("code", &self.get_code().as_u16())?;
|
||||
s.serialize_field("description", &String::from(self))?;
|
||||
s.end()
|
||||
}
|
||||
|
@ -32,11 +37,19 @@ impl Serialize for DatabaseError {
|
|||
impl From<&DatabaseError> for String {
|
||||
fn from(err: &DatabaseError) -> Self {
|
||||
match err {
|
||||
DatabaseError::InsertError => String::from("error inserting into database"),
|
||||
DatabaseError::InsertError => String::from("error on inserting into database"),
|
||||
DatabaseError::InsertGetError => {
|
||||
String::from("error retrieving new entry from database (your entry was saved)")
|
||||
String::from("error on retrieving new entry from database (your entry was saved)")
|
||||
}
|
||||
DatabaseError::NotFound => String::from("model was not found in database")
|
||||
DatabaseError::NotFound => String::from("model was not found in database"),
|
||||
DatabaseError::DeleteError => String::from("error on deleting from database"),
|
||||
DatabaseError::Protected => String::from("model is protected"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DatabaseError> for HttpResponse {
|
||||
fn from(err: DatabaseError) -> Self {
|
||||
HttpResponse::build(err.get_code()).json(err)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue