Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: convert validation errors to use failure #70

Merged
merged 2 commits into from
Oct 22, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/db/error.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use std::fmt;

use actix_web::http::StatusCode;
use diesel;
use diesel_migrations;
use failure::{Backtrace, Context, Fail};

#[derive(Debug)]
pub struct DbError {
inner: Context<DbErrorKind>,
pub status: StatusCode,
}

#[derive(Debug, Fail)]
Expand Down Expand Up @@ -43,6 +45,18 @@ impl DbError {
}
}

impl From<Context<DbErrorKind>> for DbError {
fn from(inner: Context<DbErrorKind>) -> Self {
let status = match inner.get_context() {
DbErrorKind::CollectionNotFound => StatusCode::BAD_REQUEST,
DbErrorKind::ItemNotFound => StatusCode::BAD_REQUEST,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};

Self { inner, status }
}
}

failure_boilerplate!(DbError, DbErrorKind);

from_error!(diesel::result::Error, DbError, DbErrorKind::Query);
Expand Down
86 changes: 77 additions & 9 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@

use std::fmt;

use actix_web::error::ResponseError;
use actix_web::{error::ResponseError, http::StatusCode, HttpResponse};
use failure::{Backtrace, Context, Fail};
use serde::ser::{Serialize, SerializeMap, SerializeSeq, Serializer};

use db::error::DbError;
use web::error::HawkError;
use web::error::{HawkError, ValidationError};

/// Common `Result` type.
pub type ApiResult<T> = Result<T, ApiError>;
Expand All @@ -15,6 +16,7 @@ pub type ApiResult<T> = Result<T, ApiError>;
#[derive(Debug)]
pub struct ApiError {
inner: Context<ApiErrorKind>,
status: StatusCode,
}

/// Top-level ErrorKind.
Expand All @@ -25,9 +27,80 @@ pub enum ApiErrorKind {

#[fail(display = "HAWK authentication error: {}", _0)]
Hawk(#[cause] HawkError),

#[fail(display = "{}", _0)]
Validation(#[cause] ValidationError),
}

impl From<ApiError> for HttpResponse {
fn from(inner: ApiError) -> Self {
ResponseError::error_response(&inner)
}
}

impl From<Context<ApiErrorKind>> for ApiError {
fn from(inner: Context<ApiErrorKind>) -> Self {
let status = match inner.get_context() {
ApiErrorKind::Db(error) => error.status,
ApiErrorKind::Hawk(_) => StatusCode::UNAUTHORIZED,
ApiErrorKind::Validation(_) => StatusCode::BAD_REQUEST,
};

Self { inner, status }
}
}

impl ResponseError for ApiError {
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status).json(self)
}
}

impl Serialize for ApiError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let size = if self.status == StatusCode::UNAUTHORIZED {
2
} else {
3
};

let mut map = serializer.serialize_map(Some(size))?;
map.serialize_entry("status", &self.status.as_u16())?;
map.serialize_entry("reason", self.status.canonical_reason().unwrap_or(""))?;

if self.status != StatusCode::UNAUTHORIZED {
map.serialize_entry("errors", &self.inner.get_context())?;
}

map.end()
}
}

impl Serialize for ApiErrorKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *self {
ApiErrorKind::Db(ref error) => serialize_string_to_array(serializer, error),
ApiErrorKind::Hawk(ref error) => serialize_string_to_array(serializer, error),
ApiErrorKind::Validation(ref error) => Serialize::serialize(error, serializer),
}
}
}

impl ResponseError for ApiError {}
fn serialize_string_to_array<S, V>(serializer: S, value: V) -> Result<S::Ok, S::Error>
where
S: Serializer,
V: fmt::Display,
{
let mut seq = serializer.serialize_seq(Some(1))?;
seq.serialize_element(&value.to_string())?;
seq.end()
}

// XXX: We can remove this if/when db methods return ApiError directly
impl ResponseError for DbError {}
Expand Down Expand Up @@ -55,12 +128,6 @@ macro_rules! failure_boilerplate {
Context::new(kind).into()
}
}

impl From<Context<$kind>> for $error {
fn from(inner: Context<$kind>) -> Self {
Self { inner }
}
}
};
}

Expand All @@ -78,3 +145,4 @@ macro_rules! from_error {

from_error!(DbError, ApiError, ApiErrorKind::Db);
from_error!(HawkError, ApiError, ApiErrorKind::Hawk);
from_error!(ValidationError, ApiError, ApiErrorKind::Validation);
93 changes: 92 additions & 1 deletion src/web/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ use base64::DecodeError;
use failure::{Backtrace, Context, Fail, SyncFailure};
use hawk::Error as ParseError;
use hmac::crypto_mac::{InvalidKeyLength, MacError};
use serde_json::Error as JsonError;
use serde::ser::{Serialize, SerializeSeq, Serializer};
use serde_json::{Error as JsonError, Value};
use validator;

use super::extractors::RequestErrorLocation;
use error::ApiError;

/// An error occurred during HAWK authentication.
Expand Down Expand Up @@ -60,14 +63,43 @@ pub enum HawkErrorKind {
TruncatedId,
}

/// An error occurred in an Actix extractor.
#[derive(Debug)]
pub struct ValidationError {
inner: Context<ValidationErrorKind>,
}

/// Causes of extractor errors.
#[derive(Debug, Fail)]
pub enum ValidationErrorKind {
#[fail(display = "{}", _0)]
FromDetails(String, RequestErrorLocation, Option<String>),

#[fail(display = "{}", _0)]
FromValidationErrors(#[cause] validator::ValidationErrors, RequestErrorLocation),
}

failure_boilerplate!(HawkError, HawkErrorKind);
failure_boilerplate!(ValidationError, ValidationErrorKind);

from_error!(DecodeError, ApiError, HawkErrorKind::Base64);
from_error!(InvalidKeyLength, ApiError, HawkErrorKind::InvalidKeyLength);
from_error!(JsonError, ApiError, HawkErrorKind::Json);
from_error!(MacError, ApiError, HawkErrorKind::Hmac);
from_error!(ToStrError, ApiError, HawkErrorKind::Header);

impl From<Context<HawkErrorKind>> for HawkError {
fn from(inner: Context<HawkErrorKind>) -> Self {
Self { inner }
}
}

impl From<Context<ValidationErrorKind>> for ValidationError {
fn from(inner: Context<ValidationErrorKind>) -> Self {
Self { inner }
}
}

impl From<HawkErrorKind> for ApiError {
fn from(kind: HawkErrorKind) -> Self {
let hawk_error: HawkError = Context::new(kind).into();
Expand All @@ -80,3 +112,62 @@ impl From<ParseError> for ApiError {
HawkErrorKind::Parse(SyncFailure::new(inner)).into()
}
}

impl From<ValidationErrorKind> for ApiError {
fn from(kind: ValidationErrorKind) -> Self {
let validation_error: ValidationError = Context::new(kind).into();
validation_error.into()
}
}

impl Serialize for ValidationError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Serialize::serialize(&self.inner.get_context(), serializer)
}
}

impl Serialize for ValidationErrorKind {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_seq(None)?;

match *self {
ValidationErrorKind::FromDetails(ref description, ref location, ref name) => {
seq.serialize_element(&SerializedValidationError {
description,
location,
name: name.as_ref().map(|name| &**name),
value: None,
})?;
}

ValidationErrorKind::FromValidationErrors(ref errors, ref location) => {
for (field, field_errors) in errors.clone().field_errors().iter() {
for field_error in field_errors.iter() {
seq.serialize_element(&SerializedValidationError {
description: &field_error.code,
location,
name: Some(field),
value: field_error.params.get("value"),
})?;
}
}
}
}

seq.end()
}
}

#[derive(Debug, Serialize)]
struct SerializedValidationError<'e> {
pub description: &'e str,
pub location: &'e RequestErrorLocation,
pub name: Option<&'e str>,
pub value: Option<&'e Value>,
}
Loading