Skip to content

Custom errors for validators #11

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

Merged
merged 2 commits into from
Sep 21, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
49 changes: 42 additions & 7 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::io;
use std::fmt;
use std::rc::Rc;
use std::error::Error as StdError;
use std::slice::Iter;
use std::path::{Path, PathBuf};
use std::cell::RefCell;
Expand Down Expand Up @@ -42,16 +43,26 @@ quick_error! {
filename=pos.0, line=pos.1, offset=pos.2,
path=path, text=msg)
}
Custom(message: String) {
display("{}", message)
description(message)
SerdeError(msg: String) {
display("{}", msg)
}
CustomError(pos: Option<ErrorPos>, err: Box<StdError>) {
display(x) -> ("{loc}{err}",
loc=if let &Some(ref p) = pos {
format!("{filename}:{line}:{offset}: ",
filename=p.0, line=p.1, offset=p.2)
} else {
"".to_string()
},
err=err)
cause(&**err)
}
}
}

impl ::serde::de::Error for Error {
fn custom<T: ::std::fmt::Display>(msg: T) -> Self {
ErrorEnum::Custom(format!("{}", msg)).into()
fn custom<T: fmt::Display>(msg: T) -> Self {
ErrorEnum::SerdeError(format!("{}", msg)).into()
}
}

Expand Down Expand Up @@ -85,6 +96,30 @@ impl Error {
ErrorPos((*pos.filename).clone(), pos.line, pos.line_offset),
message).into()
}

pub fn custom_error<T: StdError + 'static>(err: T)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why custom_error. I think it's custom everywhere in the rust ecosystem?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because of implementing custom at impl ::serde::de::Error for Error:

error[E0277]: the trait bound `std::string::String: std::error::Error` is not satisfied                   
  --> src/de.rs:73:28                                                                                     
   |                                                 
73 |                 return Err(Error::custom(format!("bad boolean {:?}", self.0)));                      
   |                            ^^^^^^^^^^^^^ the trait `std::error::Error` is not implemented for `std::string::String`                                                                                            
   |                                                                                                      
   = note: required by `errors::Error::custom`

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can write it as de::Error::custom instead. Presumably, this will never happen outside of the quire library itself (i.e. having de::Error in scope as well as quire::Error)

-> Error
{
ErrorEnum::CustomError(None, Box::new(err)).into()
}

pub fn custom_error_at<T: StdError + 'static>(pos: &Pos, err: T)
-> Error
{
ErrorEnum::CustomError(
Some(ErrorPos((*pos.filename).clone(), pos.line, pos.line_offset)),
Box::new(err)).into()
}

pub fn downcast_ref<T: StdError + 'static>(&self) -> Option<&T> {
match self.0 {
ErrorEnum::OpenError(_, ref e) => {
(e as &StdError).downcast_ref::<T>()
},
ErrorEnum::CustomError(_, ref e) => e.downcast_ref::<T>(),
_ => None,
}
}
}

/// List of errors that were encountered during configuration file parsing
Expand Down Expand Up @@ -170,8 +205,8 @@ pub fn add_info<T>(pos: &Pos, path: &String, result: Result<T, Error>)
-> Result<T, Error>
{
match result {
Err(Error(ErrorEnum::Custom(e))) => {
Err(Error::decode_error(pos, path, e))
Err(Error(ErrorEnum::SerdeError(e))) => {
Err(Error::decode_error(pos, path, format!("{}", e)))
}
result => result,
}
Expand Down
73 changes: 72 additions & 1 deletion src/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,10 +713,13 @@ impl Validator for Nothing {

#[cfg(test)]
mod test {
use std::fmt;
use std::rc::Rc;
use std::path::PathBuf;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::error::Error as StdError;

use serde::Deserialize;

use {Options};
Expand All @@ -728,8 +731,9 @@ mod test {
use {parse_string, ErrorList};
use validate::{Validator, Structure, Scalar, Numeric, Mapping, Sequence};
use validate::{Enum, Nothing, Directory, Anything};
use errors::ErrorCollector;
use errors::{Error, ErrorCollector};
use self::TestEnum::*;
use super::Pos;

#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
struct TestStruct {
Expand Down Expand Up @@ -1453,4 +1457,71 @@ mod test {
fn test_enum_def_tag() {
assert_eq!(parse_enum_def("!Alpha"), TestEnumDef::Alpha);
}

#[derive(Clone, Debug, PartialEq, Eq, Deserialize)]
struct Version;

#[derive(Debug)]
struct VersionError(&'static str);

impl StdError for VersionError {
fn description(&self) -> &str { "Version Error" }
fn cause(&self) -> Option<&StdError> { None }
}

impl fmt::Display for VersionError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}: {}", self.description(), self.0)
}
}

impl Version {
fn new() -> Version {
Version {}
}
}

impl Validator for Version {
fn default(&self, pos: Pos) -> Option<A> {
None
}

fn validate(&self, ast: A, err: &ErrorCollector) -> A {
match ast {
A::Scalar(pos, tag, kind, version) => {
if !version.starts_with("v") {
err.add_error(Error::custom_error_at(
&pos,
VersionError("Version must start with 'v'")))
}
A::Scalar(pos, tag, kind, version)
},
ast => {
err.add_error(Error::validation_error(
&ast.pos(), format!("Version must be a scalar value")));
ast
},
}
}
}

fn parse_version(body: &str) -> Result<Version, ErrorList> {
let validator = Version::new();
parse_string("<inline text>", body, &validator, &Options::default())
}

#[test]
fn test_custom_error() {
let err = parse_version("0.0.1").unwrap_err();
let error = err.errors().nth(0).unwrap();
assert_eq!(
format!("{}", error),
"<inline text>:1:1: Version Error: Version must start with 'v'");
match error.downcast_ref::<VersionError>() {
Some(&VersionError(msg)) => {
assert_eq!(msg, "Version must start with 'v'")
},
e => panic!("Custom error must be VersionError but was: {:?}", e),
}
}
}