Last active
December 5, 2018 13:45
-
-
Save ivanovaleksey/5f2d34243e3c070bb81adff10806e077 to your computer and use it in GitHub Desktop.
Migrate from error-chain to failure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
error_chain! { | |
foreign_links { | |
Diesel(::diesel::result::Error); | |
Json(::serde_json::Error); | |
Mqtt(::rumqtt::Error); | |
Utf8(::std::string::FromUtf8Error); | |
Uuid(::uuid::ParseError); | |
} | |
errors { | |
BadRequest | |
Nom(kind: ::nom::ErrorKind) { | |
description("parsing error") | |
display("parsing error: {:?}", kind) | |
} | |
} | |
} | |
impl<'a> From<::nom::Err<::nom::types::CompleteStr<'a>>> for Error { | |
fn from(err: ::nom::Err<::nom::types::CompleteStr<'a>>) -> Error { | |
let kind = err.into_error_kind(); | |
Error::from_kind(ErrorKind::Nom(kind)) | |
} | |
} | |
impl From<Error> for jsonrpc::Error { | |
fn from(err: Error) -> Self { | |
let code = match err { | |
Error(ErrorKind::Diesel(ref e), _) => match *e { | |
diesel::result::Error::NotFound => 404, | |
_ => 422, | |
}, | |
_ => 500, | |
}; | |
jsonrpc::Error { | |
code: jsonrpc::ErrorCode::ServerError(code), | |
message: err.description().into(), | |
data: None, | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use diesel; | |
use jsonrpc_core as jsonrpc; | |
use nom; | |
use rumqtt; | |
pub type Result<T> = ::std::result::Result<T, Error>; | |
#[derive(Debug, Fail)] | |
pub enum Error { | |
#[fail(display = "Bad request")] | |
BadRequest, | |
#[fail(display = "{}", _0)] | |
Db(diesel::result::Error), | |
#[fail(display = "{:?}", _0)] | |
ParseError(nom::ErrorKind), | |
} | |
impl From<Error> for jsonrpc::Error { | |
fn from(e: Error) -> Self { | |
let code = match e { | |
Error::Db(ref e) => match *e { | |
diesel::result::Error::NotFound => 404, | |
_ => 422, | |
}, | |
_ => 500, | |
}; | |
jsonrpc::Error { | |
code: jsonrpc::ErrorCode::ServerError(code), | |
message: e.to_string(), | |
data: None, | |
} | |
} | |
} | |
impl From<diesel::result::Error> for Error { | |
fn from(e: diesel::result::Error) -> Self { | |
Error::Db(e) | |
} | |
} | |
type NomError<'a> = nom::Err<nom::types::CompleteStr<'a>>; | |
impl<'a> From<NomError<'a>> for Error { | |
fn from(e: NomError<'a>) -> Error { | |
let kind = e.into_error_kind(); | |
Error::ParseError(kind) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment