Thiserror changeover (#3728)

* WIP remove failure from all `Cargo.toml`

* WIP remove `extern crate failure_derive`

* Use `thiserror` to fix all errors

* StoreErr is still a tuple

* Remove another set of unnecessary `.into()`s

* update fuzz tests

* update pool/fuzz dependencies in cargo.lock

* small changes based on feedback

Co-authored-by: trevyn <trevyn-git@protonmail.com>
This commit is contained in:
Yeastplume
2022-07-14 11:08:13 +01:00
committed by GitHub
parent 03b007c20e
commit a14a8e3123
75 changed files with 1795 additions and 2209 deletions
+11 -17
View File
@@ -14,9 +14,8 @@
//! High level JSON/HTTP client API
use crate::rest::{Error, ErrorKind};
use crate::rest::Error;
use crate::util::to_base64;
use failure::{Fail, ResultExt};
use hyper::body;
use hyper::header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
use hyper::{Body, Client, Request};
@@ -181,9 +180,7 @@ fn build_request(
None => Body::empty(),
Some(json) => json.into(),
})
.map_err(|e| {
ErrorKind::RequestError(format!("Bad request {} {}: {}", method, url, e)).into()
})
.map_err(|e| Error::RequestError(format!("Bad request {} {}: {}", method, url, e)))
}
pub fn create_post_request<IN>(
@@ -194,9 +191,8 @@ pub fn create_post_request<IN>(
where
IN: Serialize,
{
let json = serde_json::to_string(input).context(ErrorKind::Internal(
"Could not serialize data to JSON".to_owned(),
))?;
let json = serde_json::to_string(input)
.map_err(|e| Error::Internal(format!("Could not serialize data to JSON: {}", e)))?;
build_request(url, "POST", api_secret, Some(json))
}
@@ -205,10 +201,8 @@ where
for<'de> T: Deserialize<'de>,
{
let data = send_request(req, timeout)?;
serde_json::from_str(&data).map_err(|e| {
e.context(ErrorKind::ResponseError("Cannot parse response".to_owned()))
.into()
})
serde_json::from_str(&data)
.map_err(|e| Error::ResponseError(format!("Cannot parse response {}", e)))
}
async fn handle_request_async<T>(req: Request<Body>) -> Result<T, Error>
@@ -217,7 +211,7 @@ where
{
let data = send_request_async(req, TimeOut::default()).await?;
let ser = serde_json::from_str(&data)
.map_err(|e| e.context(ErrorKind::ResponseError("Cannot parse response".to_owned())))?;
.map_err(|e| Error::ResponseError(format!("Cannot parse response {}", e)))?;
Ok(ser)
}
@@ -237,10 +231,10 @@ async fn send_request_async(req: Request<Body>, timeout: TimeOut) -> Result<Stri
let resp = client
.request(req)
.await
.map_err(|e| ErrorKind::RequestError(format!("Cannot make request: {}", e)))?;
.map_err(|e| Error::RequestError(format!("Cannot make request: {}", e)))?;
if !resp.status().is_success() {
return Err(ErrorKind::RequestError(format!(
return Err(Error::RequestError(format!(
"Wrong response code: {} with data {:?}",
resp.status(),
resp.body()
@@ -250,7 +244,7 @@ async fn send_request_async(req: Request<Body>, timeout: TimeOut) -> Result<Stri
let raw = body::to_bytes(resp)
.await
.map_err(|e| ErrorKind::RequestError(format!("Cannot read response body: {}", e)))?;
.map_err(|e| Error::RequestError(format!("Cannot read response body: {}", e)))?;
Ok(String::from_utf8_lossy(&raw).to_string())
}
@@ -260,6 +254,6 @@ pub fn send_request(req: Request<Body>, timeout: TimeOut) -> Result<String, Erro
.basic_scheduler()
.enable_all()
.build()
.map_err(|e| ErrorKind::RequestError(format!("{}", e)))?;
.map_err(|e| Error::RequestError(format!("{}", e)))?;
rt.block_on(send_request_async(req, timeout))
}
+38 -41
View File
@@ -19,7 +19,7 @@ use crate::core::core::transaction::Transaction;
use crate::foreign::Foreign;
use crate::pool::PoolEntry;
use crate::pool::{BlockChain, PoolAdapter};
use crate::rest::ErrorKind;
use crate::rest::Error;
use crate::types::{
BlockHeaderPrintable, BlockPrintable, LocatedTxKernel, OutputListing, OutputPrintable, Tip,
Version,
@@ -126,7 +126,7 @@ pub trait ForeignRpc: Sync + Send {
height: Option<u64>,
hash: Option<String>,
commit: Option<String>,
) -> Result<BlockHeaderPrintable, ErrorKind>;
) -> Result<BlockHeaderPrintable, Error>;
/**
Networked version of [Foreign::get_block](struct.Foreign.html#method.get_block).
@@ -244,7 +244,7 @@ pub trait ForeignRpc: Sync + Send {
height: Option<u64>,
hash: Option<String>,
commit: Option<String>,
) -> Result<BlockPrintable, ErrorKind>;
) -> Result<BlockPrintable, Error>;
/**
Networked version of [Foreign::get_version](struct.Foreign.html#method.get_version).
@@ -277,7 +277,7 @@ pub trait ForeignRpc: Sync + Send {
# );
```
*/
fn get_version(&self) -> Result<Version, ErrorKind>;
fn get_version(&self) -> Result<Version, Error>;
/**
Networked version of [Foreign::get_tip](struct.Foreign.html#method.get_tip).
@@ -312,7 +312,7 @@ pub trait ForeignRpc: Sync + Send {
# );
```
*/
fn get_tip(&self) -> Result<Tip, ErrorKind>;
fn get_tip(&self) -> Result<Tip, Error>;
/**
Networked version of [Foreign::get_kernel](struct.Foreign.html#method.get_kernel).
@@ -355,7 +355,7 @@ pub trait ForeignRpc: Sync + Send {
excess: String,
min_height: Option<u64>,
max_height: Option<u64>,
) -> Result<LocatedTxKernel, ErrorKind>;
) -> Result<LocatedTxKernel, Error>;
/**
Networked version of [Foreign::get_outputs](struct.Foreign.html#method.get_outputs).
@@ -442,7 +442,7 @@ pub trait ForeignRpc: Sync + Send {
end_height: Option<u64>,
include_proof: Option<bool>,
include_merkle_proof: Option<bool>,
) -> Result<Vec<OutputPrintable>, ErrorKind>;
) -> Result<Vec<OutputPrintable>, Error>;
/**
Networked version of [Foreign::get_unspent_outputs](struct.Foreign.html#method.get_unspent_outputs).
@@ -503,7 +503,7 @@ pub trait ForeignRpc: Sync + Send {
end_index: Option<u64>,
max: u64,
include_proof: Option<bool>,
) -> Result<OutputListing, ErrorKind>;
) -> Result<OutputListing, Error>;
/**
Networked version of [Foreign::get_pmmr_indices](struct.Foreign.html#method.get_pmmr_indices).
@@ -540,7 +540,7 @@ pub trait ForeignRpc: Sync + Send {
&self,
start_block_height: u64,
end_block_height: Option<u64>,
) -> Result<OutputListing, ErrorKind>;
) -> Result<OutputListing, Error>;
/**
Networked version of [Foreign::get_pool_size](struct.Foreign.html#method.get_pool_size).
@@ -570,7 +570,7 @@ pub trait ForeignRpc: Sync + Send {
# );
```
*/
fn get_pool_size(&self) -> Result<usize, ErrorKind>;
fn get_pool_size(&self) -> Result<usize, Error>;
/**
Networked version of [Foreign::get_stempool_size](struct.Foreign.html#method.get_stempool_size).
@@ -600,7 +600,7 @@ pub trait ForeignRpc: Sync + Send {
# );
```
*/
fn get_stempool_size(&self) -> Result<usize, ErrorKind>;
fn get_stempool_size(&self) -> Result<usize, Error>;
/**
Networked version of [Foreign::get_unconfirmed_transactions](struct.Foreign.html#method.get_unconfirmed_transactions).
@@ -673,7 +673,7 @@ pub trait ForeignRpc: Sync + Send {
# );
```
*/
fn get_unconfirmed_transactions(&self) -> Result<Vec<PoolEntry>, ErrorKind>;
fn get_unconfirmed_transactions(&self) -> Result<Vec<PoolEntry>, Error>;
/**
Networked version of [Foreign::push_transaction](struct.Foreign.html#method.push_transaction).
@@ -738,7 +738,7 @@ pub trait ForeignRpc: Sync + Send {
# );
```
*/
fn push_transaction(&self, tx: Transaction, fluff: Option<bool>) -> Result<(), ErrorKind>;
fn push_transaction(&self, tx: Transaction, fluff: Option<bool>) -> Result<(), Error>;
}
impl<B, P> ForeignRpc for Foreign<B, P>
@@ -751,36 +751,36 @@ where
height: Option<u64>,
hash: Option<String>,
commit: Option<String>,
) -> Result<BlockHeaderPrintable, ErrorKind> {
) -> Result<BlockHeaderPrintable, Error> {
let mut parsed_hash: Option<Hash> = None;
if let Some(hash) = hash {
let vec = util::from_hex(&hash)
.map_err(|e| ErrorKind::Argument(format!("invalid block hash: {}", e)))?;
.map_err(|e| Error::Argument(format!("invalid block hash: {}", e)))?;
parsed_hash = Some(Hash::from_vec(&vec));
}
Foreign::get_header(self, height, parsed_hash, commit).map_err(|e| e.kind().clone())
Foreign::get_header(self, height, parsed_hash, commit)
}
fn get_block(
&self,
height: Option<u64>,
hash: Option<String>,
commit: Option<String>,
) -> Result<BlockPrintable, ErrorKind> {
) -> Result<BlockPrintable, Error> {
let mut parsed_hash: Option<Hash> = None;
if let Some(hash) = hash {
let vec = util::from_hex(&hash)
.map_err(|e| ErrorKind::Argument(format!("invalid block hash: {}", e)))?;
.map_err(|e| Error::Argument(format!("invalid block hash: {}", e)))?;
parsed_hash = Some(Hash::from_vec(&vec));
}
Foreign::get_block(self, height, parsed_hash, commit).map_err(|e| e.kind().clone())
Foreign::get_block(self, height, parsed_hash, commit)
}
fn get_version(&self) -> Result<Version, ErrorKind> {
Foreign::get_version(self).map_err(|e| e.kind().clone())
fn get_version(&self) -> Result<Version, Error> {
Foreign::get_version(self)
}
fn get_tip(&self) -> Result<Tip, ErrorKind> {
Foreign::get_tip(self).map_err(|e| e.kind().clone())
fn get_tip(&self) -> Result<Tip, Error> {
Foreign::get_tip(self)
}
fn get_kernel(
@@ -788,8 +788,8 @@ where
excess: String,
min_height: Option<u64>,
max_height: Option<u64>,
) -> Result<LocatedTxKernel, ErrorKind> {
Foreign::get_kernel(self, excess, min_height, max_height).map_err(|e| e.kind().clone())
) -> Result<LocatedTxKernel, Error> {
Foreign::get_kernel(self, excess, min_height, max_height)
}
fn get_outputs(
@@ -799,7 +799,7 @@ where
end_height: Option<u64>,
include_proof: Option<bool>,
include_merkle_proof: Option<bool>,
) -> Result<Vec<OutputPrintable>, ErrorKind> {
) -> Result<Vec<OutputPrintable>, Error> {
Foreign::get_outputs(
self,
commits,
@@ -808,7 +808,6 @@ where
include_proof,
include_merkle_proof,
)
.map_err(|e| e.kind().clone())
}
fn get_unspent_outputs(
@@ -817,33 +816,31 @@ where
end_index: Option<u64>,
max: u64,
include_proof: Option<bool>,
) -> Result<OutputListing, ErrorKind> {
) -> Result<OutputListing, Error> {
Foreign::get_unspent_outputs(self, start_index, end_index, max, include_proof)
.map_err(|e| e.kind().clone())
}
fn get_pmmr_indices(
&self,
start_block_height: u64,
end_block_height: Option<u64>,
) -> Result<OutputListing, ErrorKind> {
) -> Result<OutputListing, Error> {
Foreign::get_pmmr_indices(self, start_block_height, end_block_height)
.map_err(|e| e.kind().clone())
}
fn get_pool_size(&self) -> Result<usize, ErrorKind> {
Foreign::get_pool_size(self).map_err(|e| e.kind().clone())
fn get_pool_size(&self) -> Result<usize, Error> {
Foreign::get_pool_size(self)
}
fn get_stempool_size(&self) -> Result<usize, ErrorKind> {
Foreign::get_stempool_size(self).map_err(|e| e.kind().clone())
fn get_stempool_size(&self) -> Result<usize, Error> {
Foreign::get_stempool_size(self)
}
fn get_unconfirmed_transactions(&self) -> Result<Vec<PoolEntry>, ErrorKind> {
Foreign::get_unconfirmed_transactions(self).map_err(|e| e.kind().clone())
fn get_unconfirmed_transactions(&self) -> Result<Vec<PoolEntry>, Error> {
Foreign::get_unconfirmed_transactions(self)
}
fn push_transaction(&self, tx: Transaction, fluff: Option<bool>) -> Result<(), ErrorKind> {
Foreign::push_transaction(self, tx, fluff).map_err(|e| e.kind().clone())
fn push_transaction(&self, tx: Transaction, fluff: Option<bool>) -> Result<(), Error> {
Foreign::push_transaction(self, tx, fluff)
}
}
@@ -854,7 +851,7 @@ macro_rules! doctest_helper_json_rpc_foreign_assert_response {
// create temporary grin server, run jsonrpc request on node api, delete server, return
// json response.
{
{
/*use grin_servers::test_framework::framework::run_doctest;
use grin_util as util;
use serde_json;
@@ -888,6 +885,6 @@ macro_rules! doctest_helper_json_rpc_foreign_assert_response {
serde_json::to_string_pretty(&expected_response).unwrap()
);
}*/
}
}
};
}
+27 -24
View File
@@ -20,7 +20,6 @@ use crate::router::{Handler, ResponseFuture};
use crate::types::*;
use crate::util;
use crate::web::*;
use failure::ResultExt;
use hyper::{Body, Request, StatusCode};
use regex::Regex;
use std::sync::Weak;
@@ -43,33 +42,33 @@ impl HeaderHandler {
if let Ok(height) = input.parse() {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(BlockHeaderPrintable::from_header(&header)),
Err(_) => return Err(ErrorKind::NotFound.into()),
Err(_) => return Err(Error::NotFound),
}
}
check_block_param(&input)?;
let vec = util::from_hex(&input)
.map_err(|e| ErrorKind::Argument(format!("invalid input: {}", e)))?;
let vec =
util::from_hex(&input).map_err(|e| Error::Argument(format!("invalid input: {}", e)))?;
let h = Hash::from_vec(&vec);
let header = w(&self.chain)?
.get_block_header(&h)
.context(ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
Ok(BlockHeaderPrintable::from_header(&header))
}
fn get_header_for_output(&self, commit_id: String) -> Result<BlockHeaderPrintable, Error> {
let oid = match get_output(&self.chain, &commit_id)? {
Some((_, o)) => o,
None => return Err(ErrorKind::NotFound.into()),
None => return Err(Error::NotFound),
};
match w(&self.chain)?.get_header_for_output(oid.commitment()) {
Ok(header) => Ok(BlockHeaderPrintable::from_header(&header)),
Err(_) => Err(ErrorKind::NotFound.into()),
Err(_) => Err(Error::NotFound),
}
}
pub fn get_header_v2(&self, h: &Hash) -> Result<BlockHeaderPrintable, Error> {
let chain = w(&self.chain)?;
let header = chain.get_block_header(h).context(ErrorKind::NotFound)?;
let header = chain.get_block_header(h).map_err(|_| Error::NotFound)?;
Ok(BlockHeaderPrintable::from_header(&header))
}
@@ -83,7 +82,7 @@ impl HeaderHandler {
if let Some(height) = height {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound.into()),
Err(_) => return Err(Error::NotFound),
}
}
if let Some(hash) = hash {
@@ -92,14 +91,16 @@ impl HeaderHandler {
if let Some(commit) = commit {
let oid = match get_output_v2(&self.chain, &commit, false, false)? {
Some((_, o)) => o,
None => return Err(ErrorKind::NotFound.into()),
None => return Err(Error::NotFound),
};
match w(&self.chain)?.get_header_for_output(oid.commitment()) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound.into()),
Err(_) => return Err(Error::NotFound),
}
}
Err(ErrorKind::Argument("not a valid hash, height or output commit".to_owned()).into())
Err(Error::Argument(
"not a valid hash, height or output commit".to_owned(),
))
}
}
@@ -132,16 +133,16 @@ impl BlockHandler {
include_merkle_proof: bool,
) -> Result<BlockPrintable, Error> {
let chain = w(&self.chain)?;
let block = chain.get_block(h).context(ErrorKind::NotFound)?;
let block = chain.get_block(h).map_err(|_| Error::NotFound)?;
BlockPrintable::from_block(&block, &chain, include_proof, include_merkle_proof)
.map_err(|_| ErrorKind::Internal("chain error".to_owned()).into())
.map_err(|_| Error::Internal("chain error".to_owned()))
}
fn get_compact_block(&self, h: &Hash) -> Result<CompactBlockPrintable, Error> {
let chain = w(&self.chain)?;
let block = chain.get_block(h).context(ErrorKind::NotFound)?;
let block = chain.get_block(h).map_err(|_| Error::NotFound)?;
CompactBlockPrintable::from_compact_block(&block.into(), &chain)
.map_err(|_| ErrorKind::Internal("chain error".to_owned()).into())
.map_err(|_| Error::Internal("chain error".to_owned()))
}
// Try to decode the string as a height or a hash.
@@ -149,12 +150,12 @@ impl BlockHandler {
if let Ok(height) = input.parse() {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound.into()),
Err(_) => return Err(Error::NotFound),
}
}
check_block_param(&input)?;
let vec = util::from_hex(&input)
.map_err(|e| ErrorKind::Argument(format!("invalid input: {}", e)))?;
let vec =
util::from_hex(&input).map_err(|e| Error::Argument(format!("invalid input: {}", e)))?;
Ok(Hash::from_vec(&vec))
}
@@ -168,7 +169,7 @@ impl BlockHandler {
if let Some(height) = height {
match w(&self.chain)?.get_header_by_height(height) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound.into()),
Err(_) => return Err(Error::NotFound),
}
}
if let Some(hash) = hash {
@@ -177,14 +178,16 @@ impl BlockHandler {
if let Some(commit) = commit {
let oid = match get_output_v2(&self.chain, &commit, false, false)? {
Some((_, o)) => o,
None => return Err(ErrorKind::NotFound.into()),
None => return Err(Error::NotFound),
};
match w(&self.chain)?.get_header_for_output(oid.commitment()) {
Ok(header) => return Ok(header.hash()),
Err(_) => return Err(ErrorKind::NotFound.into()),
Err(_) => return Err(Error::NotFound),
}
}
Err(ErrorKind::Argument("not a valid hash, height or output commit".to_owned()).into())
Err(Error::Argument(
"not a valid hash, height or output commit".to_owned(),
))
}
}
@@ -193,7 +196,7 @@ fn check_block_param(input: &str) -> Result<(), Error> {
static ref RE: Regex = Regex::new(r"[0-9a-fA-F]{64}").unwrap();
}
if !RE.is_match(&input) {
return Err(ErrorKind::Argument("Not a valid hash or height.".to_owned()).into());
return Err(Error::Argument("Not a valid hash or height.".to_owned()));
}
Ok(())
}
+24 -26
View File
@@ -21,7 +21,6 @@ use crate::types::*;
use crate::util;
use crate::util::secp::pedersen::Commitment;
use crate::web::*;
use failure::ResultExt;
use hyper::{Body, Request, StatusCode};
use std::sync::Weak;
@@ -35,7 +34,7 @@ impl ChainHandler {
pub fn get_tip(&self) -> Result<Tip, Error> {
let head = w(&self.chain)?
.head()
.map_err(|e| ErrorKind::Internal(format!("can't get head: {}", e)))?;
.map_err(|e| Error::Internal(format!("can't get head: {}", e)))?;
Ok(Tip::from_tip(head))
}
}
@@ -56,7 +55,7 @@ impl ChainValidationHandler {
pub fn validate_chain(&self, fast_validation: bool) -> Result<(), Error> {
w(&self.chain)?
.validate(fast_validation)
.map_err(|_| ErrorKind::Internal("chain error".to_owned()).into())
.map_err(|_| Error::Internal("chain error".to_owned()))
}
}
@@ -144,11 +143,10 @@ impl OutputHandler {
// First check the commits length
for commit in &commits {
if commit.len() != 66 {
return Err(ErrorKind::RequestError(format!(
return Err(Error::RequestError(format!(
"invalid commit length for {}",
commit
))
.into());
)));
}
}
for commit in commits {
@@ -202,7 +200,7 @@ impl OutputHandler {
let chain = w(&self.chain)?;
let outputs = chain
.unspent_outputs_by_pmmr_index(start_index, max, end_index)
.context(ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
let out = OutputListing {
last_retrieved_index: outputs.0,
highest_index: outputs.1,
@@ -219,7 +217,7 @@ impl OutputHandler {
)
})
.collect::<Result<Vec<_>, _>>()
.context(ErrorKind::Internal("chain error".to_owned()))?,
.map_err(|_| Error::Internal("chain error".to_owned()))?,
};
Ok(out)
}
@@ -258,14 +256,14 @@ impl OutputHandler {
) -> Result<BlockOutputs, Error> {
let header = w(&self.chain)?
.get_header_by_height(block_height)
.map_err(|_| ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
// TODO - possible to compact away blocks we care about
// in the period between accepting the block and refreshing the wallet
let chain = w(&self.chain)?;
let block = chain
.get_block(&header.hash())
.map_err(|_| ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
let outputs = block
.outputs()
.iter()
@@ -274,7 +272,7 @@ impl OutputHandler {
OutputPrintable::from_output(output, &chain, Some(&header), include_proof, true)
})
.collect::<Result<Vec<_>, _>>()
.context(ErrorKind::Internal("cain error".to_owned()))?;
.map_err(|_| Error::Internal("chain error".to_owned()))?;
Ok(BlockOutputs {
header: BlockHeaderDifficultyInfo::from_header(&header),
@@ -291,14 +289,14 @@ impl OutputHandler {
) -> Result<Vec<OutputPrintable>, Error> {
let header = w(&self.chain)?
.get_header_by_height(block_height)
.map_err(|_| ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
// TODO - possible to compact away blocks we care about
// in the period between accepting the block and refreshing the wallet
let chain = w(&self.chain)?;
let block = chain
.get_block(&header.hash())
.map_err(|_| ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
let outputs = block
.outputs()
.iter()
@@ -313,7 +311,7 @@ impl OutputHandler {
)
})
.collect::<Result<Vec<_>, _>>()
.context(ErrorKind::Internal("cain error".to_owned()))?;
.map_err(|_| Error::Internal("chain error".to_owned()))?;
Ok(outputs)
}
@@ -408,11 +406,11 @@ impl KernelHandler {
.trim_end_matches('/')
.rsplit('/')
.next()
.ok_or_else(|| ErrorKind::RequestError("missing excess".into()))?;
let excess = util::from_hex(excess)
.map_err(|_| ErrorKind::RequestError("invalid excess hex".into()))?;
.ok_or_else(|| Error::RequestError("missing excess".into()))?;
let excess =
util::from_hex(excess).map_err(|_| Error::RequestError("invalid excess hex".into()))?;
if excess.len() != 33 {
return Err(ErrorKind::RequestError("invalid excess length".into()).into());
return Err(Error::RequestError("invalid excess length".into()));
}
let excess = Commitment::from_vec(excess);
@@ -427,18 +425,18 @@ impl KernelHandler {
if let Some(h) = params.get("min_height") {
let h = h
.parse()
.map_err(|_| ErrorKind::RequestError("invalid minimum height".into()))?;
.map_err(|_| Error::RequestError("invalid minimum height".into()))?;
// Default is genesis
min_height = if h == 0 { None } else { Some(h) };
}
if let Some(h) = params.get("max_height") {
let h = h
.parse()
.map_err(|_| ErrorKind::RequestError("invalid maximum height".into()))?;
.map_err(|_| Error::RequestError("invalid maximum height".into()))?;
// Default is current head
let head_height = chain
.head()
.map_err(|e| ErrorKind::Internal(format!("{}", e)))?
.map_err(|e| Error::Internal(format!("{}", e)))?
.height;
max_height = if h >= head_height { None } else { Some(h) };
}
@@ -446,7 +444,7 @@ impl KernelHandler {
let kernel = chain
.get_kernel_height(&excess, min_height, max_height)
.map_err(|e| ErrorKind::Internal(format!("{}", e)))?
.map_err(|e| Error::Internal(format!("{}", e)))?
.map(|(tx_kernel, height, mmr_index)| LocatedTxKernel {
tx_kernel,
height,
@@ -462,22 +460,22 @@ impl KernelHandler {
max_height: Option<u64>,
) -> Result<LocatedTxKernel, Error> {
let excess = util::from_hex(&excess)
.map_err(|_| ErrorKind::RequestError("invalid excess hex".into()))?;
.map_err(|_| Error::RequestError("invalid excess hex".into()))?;
if excess.len() != 33 {
return Err(ErrorKind::RequestError("invalid excess length".into()).into());
return Err(Error::RequestError("invalid excess length".into()));
}
let excess = Commitment::from_vec(excess);
let chain = w(&self.chain)?;
let kernel = chain
.get_kernel_height(&excess, min_height, max_height)
.map_err(|e| ErrorKind::Internal(format!("{}", e)))?
.map_err(|e| Error::Internal(format!("{}", e)))?
.map(|(tx_kernel, height, mmr_index)| LocatedTxKernel {
tx_kernel,
height,
mmr_index,
});
kernel.ok_or_else(|| ErrorKind::NotFound.into())
kernel.ok_or(Error::NotFound)
}
}
+3 -3
View File
@@ -74,7 +74,7 @@ impl PeerHandler {
if let Some(addr) = addr {
let peer_addr = PeerAddr(addr);
let peer_data: PeerData = w(&self.peers)?.get_peer(peer_addr).map_err(|e| {
let e: Error = ErrorKind::Internal(format!("get peer error: {:?}", e)).into();
let e: Error = Error::Internal(format!("get peer error: {:?}", e));
e
})?;
return Ok(vec![peer_data]);
@@ -87,14 +87,14 @@ impl PeerHandler {
let peer_addr = PeerAddr(addr);
w(&self.peers)?
.ban_peer(peer_addr, ReasonForBan::ManualBan)
.map_err(|e| ErrorKind::Internal(format!("ban peer error: {:?}", e)).into())
.map_err(|e| Error::Internal(format!("ban peer error: {:?}", e)))
}
pub fn unban_peer(&self, addr: SocketAddr) -> Result<(), Error> {
let peer_addr = PeerAddr(addr);
w(&self.peers)?
.unban_peer(peer_addr)
.map_err(|e| ErrorKind::Internal(format!("unban peer error: {:?}", e)).into())
.map_err(|e| Error::Internal(format!("unban peer error: {:?}", e)))
}
}
+6 -7
View File
@@ -23,7 +23,6 @@ use crate::types::*;
use crate::util;
use crate::util::RwLock;
use crate::web::*;
use failure::ResultExt;
use hyper::{Body, Request, StatusCode};
use std::sync::Weak;
@@ -97,10 +96,10 @@ where
let header = tx_pool
.blockchain
.chain_head()
.context(ErrorKind::Internal("Failed to get chain head".to_owned()))?;
.map_err(|e| Error::Internal(format!("Failed to get chain head: {}", e)))?;
tx_pool
.add_to_pool(source, tx, !fluff.unwrap_or(false), &header)
.context(ErrorKind::Internal("Failed to update pool".to_owned()))?;
.map_err(|e| Error::Internal(format!("Failed to update pool: {}", e)))?;
Ok(())
}
}
@@ -134,13 +133,13 @@ where
let wrapper: TxWrapper = parse_body(req).await?;
let tx_bin = util::from_hex(&wrapper.tx_hex)
.map_err(|e| ErrorKind::RequestError(format!("Bad request: {}", e)))?;
.map_err(|e| Error::RequestError(format!("Bad request: {}", e)))?;
// All wallet api interaction explicitly uses protocol version 1 for now.
let version = ProtocolVersion(1);
let tx: Transaction =
ser::deserialize(&mut &tx_bin[..], version, DeserializationMode::default())
.map_err(|e| ErrorKind::RequestError(format!("Bad request: {}", e)))?;
.map_err(|e| Error::RequestError(format!("Bad request: {}", e)))?;
let source = pool::TxSource::PushApi;
info!(
@@ -156,10 +155,10 @@ where
let header = tx_pool
.blockchain
.chain_head()
.context(ErrorKind::Internal("Failed to get chain head".to_owned()))?;
.map_err(|e| Error::Internal(format!("Failed to get chain head: {}", e)))?;
tx_pool
.add_to_pool(source, tx, !fluff, &header)
.context(ErrorKind::Internal("Failed to update pool".to_owned()))?;
.map_err(|e| Error::Internal(format!("Failed to update pool: {}", e)))?;
Ok(())
}
+1 -1
View File
@@ -50,7 +50,7 @@ impl StatusHandler {
pub fn get_status(&self) -> Result<Status, Error> {
let head = w(&self.chain)?
.head()
.map_err(|e| ErrorKind::Internal(format!("can't get head: {}", e)))?;
.map_err(|e| Error::Internal(format!("can't get head: {}", e)))?;
let sync_status = w(&self.sync_state)?.status();
let (api_sync_status, api_sync_info) = sync_status_to_api(sync_status);
Ok(Status::from_tip_and_peers(
+9 -12
View File
@@ -20,7 +20,6 @@ use crate::types::*;
use crate::util;
use crate::util::secp::pedersen::Commitment;
use crate::web::*;
use failure::ResultExt;
use hyper::{Body, Request, StatusCode};
use std::sync::Weak;
@@ -48,10 +47,8 @@ impl TxHashSetHandler {
// gets roots
fn get_roots(&self) -> Result<TxHashSet, Error> {
let chain = w(&self.chain)?;
let res = TxHashSet::from_head(&chain).context(ErrorKind::Internal(
"failed to read roots from txhashset".to_owned(),
))?;
Ok(res)
TxHashSet::from_head(&chain)
.map_err(|e| Error::Internal(format!("failed to read roots from txhashset: {}", e)))
}
// gets last n outputs inserted in to the tree
@@ -86,7 +83,7 @@ impl TxHashSetHandler {
let chain = w(&self.chain)?;
let outputs = chain
.unspent_outputs_by_pmmr_index(start_index, max, end_index)
.context(ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
let out = OutputListing {
last_retrieved_index: outputs.0,
highest_index: outputs.1,
@@ -95,7 +92,7 @@ impl TxHashSetHandler {
.iter()
.map(|x| OutputPrintable::from_output(x, &chain, None, true, true))
.collect::<Result<Vec<_>, _>>()
.context(ErrorKind::Internal("chain error".to_owned()))?,
.map_err(|e| Error::Internal(format!("chain error: {}", e)))?,
};
Ok(out)
}
@@ -109,7 +106,7 @@ impl TxHashSetHandler {
let chain = w(&self.chain)?;
let range = chain
.block_height_range_to_pmmr_indices(start_block_height, end_block_height)
.context(ErrorKind::NotFound)?;
.map_err(|_| Error::NotFound)?;
let out = OutputListing {
last_retrieved_index: range.0,
highest_index: range.1,
@@ -122,12 +119,12 @@ impl TxHashSetHandler {
// (to avoid having to create a new type to pass around)
fn get_merkle_proof_for_output(&self, id: &str) -> Result<OutputPrintable, Error> {
let c = util::from_hex(id)
.map_err(|_| ErrorKind::Argument(format!("Not a valid commitment: {}", id)))?;
.map_err(|_| Error::Argument(format!("Not a valid commitment: {}", id)))?;
let commit = Commitment::from_vec(c);
let chain = w(&self.chain)?;
let output_pos = chain.get_output_pos(&commit).context(ErrorKind::NotFound)?;
let merkle_proof = chain::Chain::get_merkle_proof_for_pos(&chain, commit)
.map_err(|_| ErrorKind::NotFound)?;
let output_pos = chain.get_output_pos(&commit).map_err(|_| Error::NotFound)?;
let merkle_proof =
chain::Chain::get_merkle_proof_for_pos(&chain, commit).map_err(|_| Error::NotFound)?;
Ok(OutputPrintable {
output_type: OutputType::Coinbase,
commit: Commitment::from_vec(vec![]),
+2 -2
View File
@@ -26,7 +26,7 @@ use std::sync::{Arc, Weak};
// boilerplate of dealing with `Weak`.
pub fn w<T>(weak: &Weak<T>) -> Result<Arc<T>, Error> {
weak.upgrade()
.ok_or_else(|| ErrorKind::Internal("failed to upgrade weak reference".to_owned()).into())
.ok_or_else(|| Error::Internal("failed to upgrade weak reference".to_owned()))
}
/// Internal function to retrieves an output by a given commitment
@@ -35,7 +35,7 @@ fn get_unspent(
id: &str,
) -> Result<Option<(OutputIdentifier, CommitPos)>, Error> {
let c = util::from_hex(id)
.map_err(|_| ErrorKind::Argument(format!("Not a valid commitment: {}", id)))?;
.map_err(|_| Error::Argument(format!("Not a valid commitment: {}", id)))?;
let commit = Commitment::from_vec(c);
let res = chain.get_unspent(commit)?;
Ok(res)
+1 -1
View File
@@ -33,7 +33,7 @@ impl VersionHandler {
pub fn get_version(&self) -> Result<Version, Error> {
let head = w(&self.chain)?
.head_header()
.map_err(|e| ErrorKind::Internal(format!("can't get head: {}", e)))?;
.map_err(|e| Error::Internal(format!("can't get head: {}", e)))?;
Ok(Version {
node_version: CRATE_VERSION.to_owned(),
-2
View File
@@ -19,8 +19,6 @@ use grin_pool as pool;
use grin_util as util;
#[macro_use]
extern crate failure_derive;
#[macro_use]
extern crate lazy_static;
+4 -4
View File
@@ -112,8 +112,8 @@ impl Owner {
}
pub fn reset_chain_head(&self, hash: String) -> Result<(), Error> {
let hash = Hash::from_hex(&hash)
.map_err(|_| ErrorKind::RequestError("invalid header hash".into()))?;
let hash =
Hash::from_hex(&hash).map_err(|_| Error::RequestError("invalid header hash".into()))?;
let handler = ChainResetHandler {
chain: self.chain.clone(),
sync_state: self.sync_state.clone(),
@@ -122,8 +122,8 @@ impl Owner {
}
pub fn invalidate_header(&self, hash: String) -> Result<(), Error> {
let hash = Hash::from_hex(&hash)
.map_err(|_| ErrorKind::RequestError("invalid header hash".into()))?;
let hash =
Hash::from_hex(&hash).map_err(|_| Error::RequestError("invalid header hash".into()))?;
let handler = ChainResetHandler {
chain: self.chain.clone(),
sync_state: self.sync_state.clone(),
+28 -28
View File
@@ -17,7 +17,7 @@
use crate::owner::Owner;
use crate::p2p::types::PeerInfoDisplay;
use crate::p2p::PeerData;
use crate::rest::ErrorKind;
use crate::rest::Error;
use crate::types::Status;
use std::net::SocketAddr;
@@ -70,7 +70,7 @@ pub trait OwnerRpc: Sync + Send {
# );
```
*/
fn get_status(&self) -> Result<Status, ErrorKind>;
fn get_status(&self) -> Result<Status, Error>;
/**
Networked version of [Owner::validate_chain](struct.Owner.html#method.validate_chain).
@@ -100,7 +100,7 @@ pub trait OwnerRpc: Sync + Send {
# );
```
*/
fn validate_chain(&self, assume_valid_rangeproofs_kernels: bool) -> Result<(), ErrorKind>;
fn validate_chain(&self, assume_valid_rangeproofs_kernels: bool) -> Result<(), Error>;
/**
Networked version of [Owner::compact_chain](struct.Owner.html#method.compact_chain).
@@ -130,11 +130,11 @@ pub trait OwnerRpc: Sync + Send {
# );
```
*/
fn compact_chain(&self) -> Result<(), ErrorKind>;
fn compact_chain(&self) -> Result<(), Error>;
fn reset_chain_head(&self, hash: String) -> Result<(), ErrorKind>;
fn reset_chain_head(&self, hash: String) -> Result<(), Error>;
fn invalidate_header(&self, hash: String) -> Result<(), ErrorKind>;
fn invalidate_header(&self, hash: String) -> Result<(), Error>;
/**
Networked version of [Owner::get_peers](struct.Owner.html#method.get_peers).
@@ -176,7 +176,7 @@ pub trait OwnerRpc: Sync + Send {
# );
```
*/
fn get_peers(&self, peer_addr: Option<SocketAddr>) -> Result<Vec<PeerData>, ErrorKind>;
fn get_peers(&self, peer_addr: Option<SocketAddr>) -> Result<Vec<PeerData>, Error>;
/**
Networked version of [Owner::get_connected_peers](struct.Owner.html#method.get_connected_peers).
@@ -295,7 +295,7 @@ pub trait OwnerRpc: Sync + Send {
# );
```
*/
fn get_connected_peers(&self) -> Result<Vec<PeerInfoDisplay>, ErrorKind>;
fn get_connected_peers(&self) -> Result<Vec<PeerInfoDisplay>, Error>;
/**
Networked version of [Owner::ban_peer](struct.Owner.html#method.ban_peer).
@@ -325,7 +325,7 @@ pub trait OwnerRpc: Sync + Send {
# );
```
*/
fn ban_peer(&self, peer_addr: SocketAddr) -> Result<(), ErrorKind>;
fn ban_peer(&self, peer_addr: SocketAddr) -> Result<(), Error>;
/**
Networked version of [Owner::unban_peer](struct.Owner.html#method.unban_peer).
@@ -355,44 +355,44 @@ pub trait OwnerRpc: Sync + Send {
# );
```
*/
fn unban_peer(&self, peer_addr: SocketAddr) -> Result<(), ErrorKind>;
fn unban_peer(&self, peer_addr: SocketAddr) -> Result<(), Error>;
}
impl OwnerRpc for Owner {
fn get_status(&self) -> Result<Status, ErrorKind> {
Owner::get_status(self).map_err(|e| e.kind().clone())
fn get_status(&self) -> Result<Status, Error> {
Owner::get_status(self)
}
fn validate_chain(&self, assume_valid_rangeproofs_kernels: bool) -> Result<(), ErrorKind> {
Owner::validate_chain(self, assume_valid_rangeproofs_kernels).map_err(|e| e.kind().clone())
fn validate_chain(&self, assume_valid_rangeproofs_kernels: bool) -> Result<(), Error> {
Owner::validate_chain(self, assume_valid_rangeproofs_kernels)
}
fn reset_chain_head(&self, hash: String) -> Result<(), ErrorKind> {
Owner::reset_chain_head(self, hash).map_err(|e| e.kind().clone())
fn reset_chain_head(&self, hash: String) -> Result<(), Error> {
Owner::reset_chain_head(self, hash)
}
fn invalidate_header(&self, hash: String) -> Result<(), ErrorKind> {
Owner::invalidate_header(self, hash).map_err(|e| e.kind().clone())
fn invalidate_header(&self, hash: String) -> Result<(), Error> {
Owner::invalidate_header(self, hash)
}
fn compact_chain(&self) -> Result<(), ErrorKind> {
Owner::compact_chain(self).map_err(|e| e.kind().clone())
fn compact_chain(&self) -> Result<(), Error> {
Owner::compact_chain(self)
}
fn get_peers(&self, addr: Option<SocketAddr>) -> Result<Vec<PeerData>, ErrorKind> {
Owner::get_peers(self, addr).map_err(|e| e.kind().clone())
fn get_peers(&self, addr: Option<SocketAddr>) -> Result<Vec<PeerData>, Error> {
Owner::get_peers(self, addr)
}
fn get_connected_peers(&self) -> Result<Vec<PeerInfoDisplay>, ErrorKind> {
Owner::get_connected_peers(self).map_err(|e| e.kind().clone())
fn get_connected_peers(&self) -> Result<Vec<PeerInfoDisplay>, Error> {
Owner::get_connected_peers(self)
}
fn ban_peer(&self, addr: SocketAddr) -> Result<(), ErrorKind> {
Owner::ban_peer(self, addr).map_err(|e| e.kind().clone())
fn ban_peer(&self, addr: SocketAddr) -> Result<(), Error> {
Owner::ban_peer(self, addr)
}
fn unban_peer(&self, addr: SocketAddr) -> Result<(), ErrorKind> {
Owner::unban_peer(self, addr).map_err(|e| e.kind().clone())
fn unban_peer(&self, addr: SocketAddr) -> Result<(), Error> {
Owner::unban_peer(self, addr)
}
}
+28 -85
View File
@@ -20,7 +20,6 @@
use crate::router::{Handler, HandlerObj, ResponseFuture, Router, RouterError};
use crate::web::response;
use failure::{Backtrace, Context, Fail, ResultExt};
use futures::channel::oneshot;
use futures::TryStreamExt;
use hyper::server::accept;
@@ -28,7 +27,6 @@ use hyper::service::make_service_fn;
use hyper::{Body, Request, Server, StatusCode};
use rustls::internal::pemfile;
use std::convert::Infallible;
use std::fmt::{self, Display};
use std::fs::File;
use std::net::SocketAddr;
use std::sync::Arc;
@@ -39,76 +37,28 @@ use tokio::stream::StreamExt;
use tokio_rustls::TlsAcceptor;
/// Errors that can be returned by an ApiEndpoint implementation.
#[derive(Debug)]
pub struct Error {
inner: Context<ErrorKind>,
}
#[derive(Clone, Eq, PartialEq, Debug, Fail, Serialize, Deserialize)]
pub enum ErrorKind {
#[fail(display = "Internal error: {}", _0)]
#[derive(Clone, Eq, PartialEq, Debug, thiserror::Error, Serialize, Deserialize)]
pub enum Error {
#[error("Internal error: {0}")]
Internal(String),
#[fail(display = "Bad arguments: {}", _0)]
#[error("Bad arguments: {0}")]
Argument(String),
#[fail(display = "Not found.")]
#[error("Not found.")]
NotFound,
#[fail(display = "Request error: {}", _0)]
#[error("Request error: {0}")]
RequestError(String),
#[fail(display = "ResponseError error: {}", _0)]
#[error("ResponseError error: {0}")]
ResponseError(String),
#[fail(display = "Router error: {}", _0)]
Router(RouterError),
}
impl Fail for Error {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(&self.inner, f)
}
}
impl Error {
pub fn kind(&self) -> &ErrorKind {
self.inner.get_context()
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Error {
Error {
inner: Context::new(kind),
}
}
}
impl From<Context<ErrorKind>> for Error {
fn from(inner: Context<ErrorKind>) -> Error {
Error { inner: inner }
}
}
impl From<RouterError> for Error {
fn from(error: RouterError) -> Error {
Error {
inner: Context::new(ErrorKind::Router(error)),
}
}
#[error("Router error: {source}")]
Router {
#[from]
source: RouterError,
},
}
impl From<crate::chain::Error> for Error {
fn from(error: crate::chain::Error) -> Error {
Error {
inner: Context::new(ErrorKind::Internal(error.to_string())),
}
Error::Internal(error.to_string())
}
}
@@ -128,27 +78,24 @@ impl TLSConfig {
}
fn load_certs(&self) -> Result<Vec<rustls::Certificate>, Error> {
let certfile = File::open(&self.certificate).context(ErrorKind::Internal(format!(
"failed to open file {}",
self.certificate
)))?;
let certfile = File::open(&self.certificate).map_err(|e| {
Error::Internal(format!("failed to open file {} {}", self.certificate, e))
})?;
let mut reader = io::BufReader::new(certfile);
pemfile::certs(&mut reader)
.map_err(|_| ErrorKind::Internal("failed to load certificate".to_string()).into())
.map_err(|_| Error::Internal("failed to load certificate".to_string()))
}
fn load_private_key(&self) -> Result<rustls::PrivateKey, Error> {
let keyfile = File::open(&self.private_key).context(ErrorKind::Internal(format!(
"failed to open file {}",
self.private_key
)))?;
let keyfile = File::open(&self.private_key)
.map_err(|e| Error::Internal(format!("failed to open private key file {}", e)))?;
let mut reader = io::BufReader::new(keyfile);
let keys = pemfile::pkcs8_private_keys(&mut reader)
.map_err(|_| ErrorKind::Internal("failed to load private key".to_string()))?;
.map_err(|_| Error::Internal("failed to load private key".to_string()))?;
if keys.len() != 1 {
return Err(ErrorKind::Internal("expected a single private key".to_string()).into());
return Err(Error::Internal("expected a single private key".to_string()));
}
Ok(keys[0].clone())
}
@@ -158,9 +105,7 @@ impl TLSConfig {
let key = self.load_private_key()?;
let mut cfg = rustls::ServerConfig::new(rustls::NoClientAuth::new());
cfg.set_single_cert(certs, key)
.context(ErrorKind::Internal(
"set single certificate failed".to_string(),
))?;
.map_err(|e| Error::Internal(format!("set single certificate failed {}", e)))?;
Ok(Arc::new(cfg))
}
}
@@ -202,10 +147,9 @@ impl ApiServer {
api_chan: &'static mut (oneshot::Sender<()>, oneshot::Receiver<()>),
) -> Result<thread::JoinHandle<()>, Error> {
if self.shutdown_sender.is_some() {
return Err(ErrorKind::Internal(
return Err(Error::Internal(
"Can't start HTTP API server, it's running already".to_string(),
)
.into());
));
}
let rx = &mut api_chan.1;
let tx = &mut api_chan.0;
@@ -238,7 +182,7 @@ impl ApiServer {
eprintln!("HTTP API server error: {}", e)
}
})
.map_err(|_| ErrorKind::Internal("failed to spawn API thread".to_string()).into())
.map_err(|_| Error::Internal("failed to spawn API thread".to_string()))
}
/// Starts the TLS ApiServer at the provided address.
@@ -251,10 +195,9 @@ impl ApiServer {
api_chan: &'static mut (oneshot::Sender<()>, oneshot::Receiver<()>),
) -> Result<thread::JoinHandle<()>, Error> {
if self.shutdown_sender.is_some() {
return Err(ErrorKind::Internal(
return Err(Error::Internal(
"Can't start HTTPS API server, it's running already".to_string(),
)
.into());
));
}
let rx = &mut api_chan.1;
@@ -296,7 +239,7 @@ impl ApiServer {
eprintln!("HTTP API server error: {}", e)
}
})
.map_err(|_| ErrorKind::Internal("failed to spawn API thread".to_string()).into())
.map_err(|_| Error::Internal("failed to spawn API thread".to_string()))
}
/// Stops the API server, it panics in case of error
+4 -4
View File
@@ -86,13 +86,13 @@ pub trait Handler {
}
}
#[derive(Clone, Fail, Eq, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, thiserror::Error, Eq, Debug, PartialEq, Serialize, Deserialize)]
pub enum RouterError {
#[fail(display = "Route already exists")]
#[error("Route already exists")]
RouteAlreadyExists,
#[fail(display = "Route not found")]
#[error("Route not found")]
RouteNotFound,
#[fail(display = "Value not found")]
#[error("Value not found")]
NoValue,
}
+11 -13
View File
@@ -16,10 +16,10 @@ where
{
let raw = body::to_bytes(req.into_body())
.await
.map_err(|e| ErrorKind::RequestError(format!("Failed to read request: {}", e)))?;
.map_err(|e| Error::RequestError(format!("Failed to read request: {}", e)))?;
serde_json::from_reader(raw.bytes())
.map_err(|e| ErrorKind::RequestError(format!("Invalid request body: {}", e)).into())
.map_err(|e| Error::RequestError(format!("Invalid request body: {}", e)))
}
/// Convert Result to ResponseFuture
@@ -29,16 +29,14 @@ where
{
match res {
Ok(s) => json_response_pretty(&s),
Err(e) => match e.kind() {
ErrorKind::Argument(msg) => response(StatusCode::BAD_REQUEST, msg.clone()),
ErrorKind::RequestError(msg) => response(StatusCode::BAD_REQUEST, msg.clone()),
ErrorKind::NotFound => response(StatusCode::NOT_FOUND, ""),
ErrorKind::Internal(msg) => response(StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
ErrorKind::ResponseError(msg) => {
response(StatusCode::INTERNAL_SERVER_ERROR, msg.clone())
}
Err(e) => match e {
Error::Argument(msg) => response(StatusCode::BAD_REQUEST, msg.clone()),
Error::RequestError(msg) => response(StatusCode::BAD_REQUEST, msg.clone()),
Error::NotFound => response(StatusCode::NOT_FOUND, ""),
Error::Internal(msg) => response(StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
Error::ResponseError(msg) => response(StatusCode::INTERNAL_SERVER_ERROR, msg.clone()),
// place holder
ErrorKind::Router(_) => response(StatusCode::INTERNAL_SERVER_ERROR, ""),
Error::Router { .. } => response(StatusCode::INTERNAL_SERVER_ERROR, ""),
},
}
}
@@ -147,7 +145,7 @@ macro_rules! must_get_query(
($req: expr) =>(
match $req.uri().query() {
Some(q) => q,
None => return Err(ErrorKind::RequestError("no query string".to_owned()).into()),
None => return Err(Error::RequestError("no query string".to_owned())),
}
));
@@ -158,7 +156,7 @@ macro_rules! parse_param(
None => $default,
Some(val) => match val.parse() {
Ok(val) => val,
Err(_) => return Err(ErrorKind::RequestError(format!("invalid value of parameter {}", $name)).into()),
Err(_) => return Err(Error::RequestError(format!("invalid value of parameter {}", $name))),
}
}
));