Skip to content

Commit

Permalink
Merge pull request #217 from manifest/feature/extract-error
Browse files Browse the repository at this point in the history
Allow customization of extract::error::Error
  • Loading branch information
lnicola authored Sep 6, 2019
2 parents 8f027c5 + 3d61873 commit bd00f29
Showing 1 changed file with 30 additions and 11 deletions.
41 changes: 30 additions & 11 deletions src/extract/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,28 @@ use http::status::StatusCode;
#[derive(Debug)]
pub struct Error {
kind: Kind,
inner: crate::Error,
}

#[derive(Debug)]
enum Kind {
Missing,
Invalid(String),
Web(crate::Error),
Invalid,
Web,
}

impl Error {
/// The data is missing from the HTTP request.
pub fn missing_argument() -> Error {
Error { kind: Missing }
Self::missing(crate::Error::from(StatusCode::BAD_REQUEST))
}

/// The data is missing from the HTTP request.
pub fn missing(inner: crate::Error) -> Error {
Error {
kind: Missing,
inner,
}
}

/// Returns `true` when the error represents missing data from the HTTP
Expand All @@ -32,14 +41,24 @@ impl Error {

/// The data is in an invalid format and cannot be extracted.
pub fn invalid_argument<T: ToString>(reason: &T) -> Error {
Error { kind: Invalid(reason.to_string()) }
let mut inner = crate::Error::from(StatusCode::BAD_REQUEST);
inner.set_detail(&reason.to_string());
Self::invalid(inner)
}

/// The data is in an invalid format and cannot be extracted.
pub fn invalid(inner: crate::Error) -> Error {
Error {
kind: Invalid,
inner,
}
}

/// Returns `true` when the data is in an invalid format and cannot be
/// extracted.
pub fn is_invalid_argument(&self) -> bool {
match self.kind {
Invalid(_) => true,
Invalid => true,
_ => false,
}
}
Expand All @@ -51,15 +70,15 @@ impl Error {

impl From<Error> for crate::Error {
fn from(err: Error) -> Self {
match err.kind {
Missing | Invalid(_) => crate::Error::from(StatusCode::BAD_REQUEST),
Web(err) => err,
}
err.inner
}
}

impl From<crate::Error> for Error {
fn from(err: crate::Error) -> Self {
Error { kind: Web(err) }
fn from(inner: crate::Error) -> Self {
Error {
kind: Web,
inner,
}
}
}

0 comments on commit bd00f29

Please sign in to comment.