Expunge error-chain (feat. tomaka) (#2662)

* Remove error_chain

* Expunge error-chain from rpc and service.

* Expunge from transaction pool.

* Expunge from node/cli

* Expunge from keystore.

* Remove some boilerplate.

* Fix remaining stuff.

* Improve on deprecation message.

* Fix issues.

* Fix trnsaction pool tests.

* Fix the rest.

* Fix borked merge.

* Update lock
This commit is contained in:
Tomasz Drwięga
2019-05-24 11:35:31 +02:00
committed by Gavin Wood
parent 69ffec5822
commit c162fc5ff1
68 changed files with 951 additions and 1158 deletions
+36 -33
View File
@@ -16,35 +16,37 @@
//! Authoring RPC module errors.
use error_chain::*;
use client;
use transaction_pool::txpool;
use crate::rpc;
use crate::errors;
error_chain! {
foreign_links {
Client(client::error::Error) #[doc = "Client error"];
}
links {
Pool(txpool::error::Error, txpool::error::ErrorKind) #[doc = "Pool error"];
}
errors {
/// Not implemented yet
Unimplemented {
description("not yet implemented"),
display("Method Not Implemented"),
}
/// Incorrect extrinsic format.
BadFormat {
description("bad format"),
display("Invalid extrinsic format"),
}
/// Verification error
Verification(e: Box<::std::error::Error + Send>) {
description("extrinsic verification error"),
display("Extrinsic verification error: {}", e.description()),
/// Author RPC Result type.
pub type Result<T> = std::result::Result<T, Error>;
/// Author RPC errors.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Client error.
Client(client::error::Error),
/// Transaction pool error,
Pool(txpool::error::Error),
/// Verification error
#[display(fmt="Extrinsic verification error: {}", "_0.description()")]
Verification(Box<::std::error::Error + Send>),
/// Incorrect extrinsic format.
#[display(fmt="Invalid extrinsic format")]
BadFormat,
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Client(ref err) => Some(err),
Error::Pool(ref err) => Some(err),
Error::Verification(ref err) => Some(&**err),
_ => None,
}
}
}
@@ -73,49 +75,50 @@ const POOL_IMMEDIATELY_DROPPED: i64 = POOL_INVALID_TX + 6;
impl From<Error> for rpc::Error {
fn from(e: Error) -> Self {
use txpool::error::{Error as PoolError};
match e {
Error(ErrorKind::Unimplemented, _) => errors::unimplemented(),
Error(ErrorKind::BadFormat, _) => rpc::Error {
Error::BadFormat => rpc::Error {
code: rpc::ErrorCode::ServerError(BAD_FORMAT),
message: "Extrinsic has invalid format.".into(),
data: None,
},
Error(ErrorKind::Verification(e), _) => rpc::Error {
Error::Verification(e) => rpc::Error {
code: rpc::ErrorCode::ServerError(VERIFICATION_ERROR),
message: e.description().into(),
data: Some(format!("{:?}", e).into()),
},
Error(ErrorKind::Pool(txpool::error::ErrorKind::InvalidTransaction(code)), _) => rpc::Error {
Error::Pool(PoolError::InvalidTransaction(code)) => rpc::Error {
code: rpc::ErrorCode::ServerError(POOL_INVALID_TX),
message: "Invalid Transaction".into(),
data: Some(code.into()),
},
Error(ErrorKind::Pool(txpool::error::ErrorKind::UnknownTransactionValidity(code)), _) => rpc::Error {
Error::Pool(PoolError::UnknownTransactionValidity(code)) => rpc::Error {
code: rpc::ErrorCode::ServerError(POOL_UNKNOWN_VALIDITY),
message: "Unknown Transaction Validity".into(),
data: Some(code.into()),
},
Error(ErrorKind::Pool(txpool::error::ErrorKind::TemporarilyBanned), _) => rpc::Error {
Error::Pool(PoolError::TemporarilyBanned) => rpc::Error {
code: rpc::ErrorCode::ServerError(POOL_TEMPORARILY_BANNED),
message: "Transaction is temporarily banned".into(),
data: None,
},
Error(ErrorKind::Pool(txpool::error::ErrorKind::AlreadyImported(hash)), _) => rpc::Error {
Error::Pool(PoolError::AlreadyImported(hash)) => rpc::Error {
code: rpc::ErrorCode::ServerError(POOL_ALREADY_IMPORTED),
message: "Transaction Already Imported".into(),
data: Some(format!("{:?}", hash).into()),
},
Error(ErrorKind::Pool(txpool::error::ErrorKind::TooLowPriority(old, new)), _) => rpc::Error {
Error::Pool(PoolError::TooLowPriority { old, new }) => rpc::Error {
code: rpc::ErrorCode::ServerError(POOL_TOO_LOW_PRIORITY),
message: format!("Priority is too low: ({} vs {})", old, new),
data: Some("The transaction has too low priority to replace another transaction already in the pool.".into()),
},
Error(ErrorKind::Pool(txpool::error::ErrorKind::CycleDetected), _) => rpc::Error {
Error::Pool(PoolError::CycleDetected) => rpc::Error {
code: rpc::ErrorCode::ServerError(POOL_CYCLE_DETECTED),
message: "Cycle Detected".into(),
data: None,
},
Error(ErrorKind::Pool(txpool::error::ErrorKind::ImmediatelyDropped), _) => rpc::Error {
Error::Pool(PoolError::ImmediatelyDropped) => rpc::Error {
code: rpc::ErrorCode::ServerError(POOL_IMMEDIATELY_DROPPED),
message: "Immediately Dropped" .into(),
data: Some("The transaction couldn't enter the pool because of the limit".into()),
+5 -4
View File
@@ -104,13 +104,13 @@ impl<B, E, P, RA> AuthorApi<ExHash<P>, BlockHash<P>> for Author<B, E, P, RA> whe
type Metadata = crate::metadata::Metadata;
fn submit_extrinsic(&self, ext: Bytes) -> Result<ExHash<P>> {
let xt = Decode::decode(&mut &ext[..]).ok_or(error::Error::from(error::ErrorKind::BadFormat))?;
let xt = Decode::decode(&mut &ext[..]).ok_or(error::Error::BadFormat)?;
let best_block_hash = self.client.info()?.chain.best_hash;
self.pool
.submit_one(&generic::BlockId::hash(best_block_hash), xt)
.map_err(|e| e.into_pool_error()
.map(Into::into)
.unwrap_or_else(|e| error::ErrorKind::Verification(Box::new(e)).into())
.unwrap_or_else(|e| error::Error::Verification(Box::new(e)).into())
)
}
@@ -121,12 +121,13 @@ impl<B, E, P, RA> AuthorApi<ExHash<P>, BlockHash<P>> for Author<B, E, P, RA> whe
fn watch_extrinsic(&self, _metadata: Self::Metadata, subscriber: Subscriber<Status<ExHash<P>, BlockHash<P>>>, xt: Bytes) {
let submit = || -> Result<_> {
let best_block_hash = self.client.info()?.chain.best_hash;
let dxt = <<P as PoolChainApi>::Block as traits::Block>::Extrinsic::decode(&mut &xt[..]).ok_or(error::Error::from(error::ErrorKind::BadFormat))?;
let dxt = <<P as PoolChainApi>::Block as traits::Block>::Extrinsic::decode(&mut &xt[..])
.ok_or(error::Error::BadFormat)?;
self.pool
.submit_and_watch(&generic::BlockId::hash(best_block_hash), dxt)
.map_err(|e| e.into_pool_error()
.map(Into::into)
.unwrap_or_else(|e| error::ErrorKind::Verification(Box::new(e)).into())
.unwrap_or_else(|e| error::Error::Verification(Box::new(e)).into())
)
};
+25 -16
View File
@@ -14,33 +14,42 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use error_chain::*;
use client;
use crate::rpc;
use crate::errors;
pub use internal_errors::*;
#[allow(deprecated)]
mod internal_errors {
use super::*;
error_chain! {
foreign_links {
Client(client::error::Error) #[doc = "Client error"];
}
errors {
/// Not implemented yet
Unimplemented {
description("not yet implemented"),
display("Method Not Implemented"),
}
/// Chain RPC Result type.
pub type Result<T> = std::result::Result<T, Error>;
/// Chain RPC errors.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Client error.
Client(client::error::Error),
/// Other error type.
Other(String),
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Client(ref err) => Some(err),
_ => None,
}
}
}
/// Base error code for all chain errors.
const BASE_ERROR: i64 = 3000;
impl From<Error> for rpc::Error {
fn from(e: Error) -> Self {
match e {
Error(ErrorKind::Unimplemented, _) => errors::unimplemented(),
Error::Other(message) => rpc::Error {
code: rpc::ErrorCode::ServerError(BASE_ERROR + 1),
message,
data: None,
},
e => errors::internal(e),
}
}
+1 -1
View File
@@ -145,7 +145,7 @@ impl<B, E, Block, RA> Chain<B, E, Block, RA> where
let header = best_block_hash()
.and_then(|hash| self.header(hash.into()))
.and_then(|header| {
header.ok_or_else(|| self::error::ErrorKind::Unimplemented.into())
header.ok_or_else(|| "Best header missing.".to_owned().into())
})
.map_err(Into::into);
-8
View File
@@ -17,14 +17,6 @@
use crate::rpc;
use log::warn;
pub fn unimplemented() -> rpc::Error {
rpc::Error {
code: rpc::ErrorCode::ServerError(1),
message: "Not implemented yet".into(),
data: None,
}
}
pub fn internal<E: ::std::fmt::Debug>(e: E) -> rpc::Error {
warn!("Unknown error: {:?}", e);
rpc::Error {
+29 -16
View File
@@ -14,34 +14,47 @@
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use error_chain::*;
use client;
use crate::rpc;
use crate::errors;
error_chain! {
foreign_links {
Client(client::error::Error) #[doc = "Client error"];
}
/// State RPC Result type.
pub type Result<T> = std::result::Result<T, Error>;
errors {
/// Provided block range couldn't be resolved to a list of blocks.
InvalidBlockRange(from: String, to: String, details: String) {
description("Invalid block range"),
display("Cannot resolve a block range ['{:?}' ... '{:?}]. {}", from, to, details),
}
/// Not implemented yet
Unimplemented {
description("not implemented yet"),
display("Method Not Implemented"),
/// State RPC errors.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Client error.
Client(client::error::Error),
/// Provided block range couldn't be resolved to a list of blocks.
#[display(fmt = "Cannot resolve a block range ['{:?}' ... '{:?}]. {}", from, to, details)]
InvalidBlockRange {
from: String,
to: String,
details: String,
},
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Client(ref err) => Some(err),
_ => None,
}
}
}
/// Base code for all state errors.
const BASE_ERROR: i64 = 4000;
impl From<Error> for rpc::Error {
fn from(e: Error) -> Self {
match e {
Error(ErrorKind::Unimplemented, _) => errors::unimplemented(),
Error::InvalidBlockRange { .. } => rpc::Error {
code: rpc::ErrorCode::ServerError(BASE_ERROR + 1),
message: format!("{}", e),
data: None,
},
e => errors::internal(e),
}
}
+18 -9
View File
@@ -22,7 +22,6 @@ use std::{
sync::Arc,
};
use error_chain::bail;
use log::{warn, trace};
use client::{self, Client, CallExecutor, BlockchainEvents, runtime_api::Metadata};
use jsonrpc_derive::rpc;
@@ -148,11 +147,15 @@ pub trait StateApi<Hash> {
/// New storage subscription
#[pubsub(subscription = "state_storage", subscribe, name = "state_subscribeStorage")]
fn subscribe_storage(&self, metadata: Self::Metadata, subscriber: Subscriber<StorageChangeSet<Hash>>, keys: Option<Vec<StorageKey>>);
fn subscribe_storage(
&self, metadata: Self::Metadata, subscriber: Subscriber<StorageChangeSet<Hash>>, keys: Option<Vec<StorageKey>>
);
/// Unsubscribe from storage subscription
#[pubsub(subscription = "state_storage", unsubscribe, name = "state_unsubscribeStorage")]
fn unsubscribe_storage(&self, metadata: Option<Self::Metadata>, id: SubscriptionId) -> RpcResult<bool>;
fn unsubscribe_storage(
&self, metadata: Option<Self::Metadata>, id: SubscriptionId
) -> RpcResult<bool>;
}
/// State API with subscriptions support.
@@ -213,7 +216,7 @@ impl<B, E, Block: BlockT, RA> State<B, E, Block, RA> where
blocks.push(hdr.hash());
last = hdr;
} else {
bail!(invalid_block_range(
return Err(invalid_block_range(
Some(from),
Some(to),
format!("Parent of {} ({}) not found", last.number(), last.hash()),
@@ -221,7 +224,7 @@ impl<B, E, Block: BlockT, RA> State<B, E, Block, RA> where
}
}
if last.hash() != from.hash() {
bail!(invalid_block_range(
return Err(invalid_block_range(
Some(from),
Some(to),
format!("Expected to reach `from`, got {} ({})", last.number(), last.hash()),
@@ -241,7 +244,7 @@ impl<B, E, Block: BlockT, RA> State<B, E, Block, RA> where
filtered_range,
})
},
(from, to) => bail!(
(from, to) => Err(
invalid_block_range(from.as_ref(), to.as_ref(), "Invalid range or unknown block".into())
),
}
@@ -483,7 +486,9 @@ impl<B, E, Block, RA> StateApi<Block::Hash> for State<B, E, Block, RA> where
}
fn subscribe_runtime_version(&self, _meta: Self::Metadata, subscriber: Subscriber<RuntimeVersion>) {
let stream = match self.client.storage_changes_notification_stream(Some(&[StorageKey(storage::well_known_keys::CODE.to_vec())])) {
let stream = match self.client.storage_changes_notification_stream(
Some(&[StorageKey(storage::well_known_keys::CODE.to_vec())])
) {
Ok(stream) => stream,
Err(err) => {
let _ = subscriber.reject(error::Error::from(err).into());
@@ -551,11 +556,15 @@ pub(crate) fn split_range(size: usize, middle: Option<usize>) -> (Range<usize>,
(range1, range2)
}
fn invalid_block_range<H: Header>(from: Option<&H>, to: Option<&H>, reason: String) -> error::ErrorKind {
fn invalid_block_range<H: Header>(from: Option<&H>, to: Option<&H>, reason: String) -> error::Error {
let to_string = |x: Option<&H>| match x {
None => "unknown hash".into(),
Some(h) => format!("{} ({})", h.number(), h.hash()),
};
error::ErrorKind::InvalidBlockRange(to_string(from), to_string(to), reason)
error::Error::InvalidBlockRange {
from: to_string(from),
to: to_string(to),
details: reason,
}
}
+2 -2
View File
@@ -15,7 +15,7 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use self::error::{Error, ErrorKind};
use self::error::Error;
use assert_matches::assert_matches;
use consensus::BlockOrigin;
@@ -80,7 +80,7 @@ fn should_call_contract() {
assert_matches!(
client.call("balanceOf".into(), Bytes(vec![1,2,3]), Some(genesis_hash).into()),
Err(Error(ErrorKind::Client(client::error::Error::Execution(_)), _))
Err(Error::Client(client::error::Error::Execution(_)))
)
}
+16 -23
View File
@@ -16,40 +16,33 @@
//! System RPC module errors.
use error_chain::*;
use crate::rpc;
use crate::errors;
use crate::system::helpers::Health;
error_chain! {
errors {
/// Node is not fully functional
NotHealthy(h: Health) {
description("node is not healthy"),
display("Node is not fully functional: {}", h)
}
/// System RPC Result type.
pub type Result<T> = std::result::Result<T, Error>;
/// Not implemented yet
Unimplemented {
description("not yet implemented"),
display("Method Not Implemented"),
}
}
/// System RPC errors.
#[derive(Debug, derive_more::Display, derive_more::From)]
pub enum Error {
/// Provided block range couldn't be resolved to a list of blocks.
#[display(fmt = "Node is not fully functional: {}", _0)]
NotHealthy(Health),
}
const ERROR: i64 = 2000;
impl std::error::Error for Error {}
/// Base code for all system errors.
const BASE_ERROR: i64 = 2000;
impl From<Error> for rpc::Error {
fn from(e: Error) -> Self {
match e {
Error(ErrorKind::Unimplemented, _) => errors::unimplemented(),
Error(ErrorKind::NotHealthy(h), _) => rpc::Error {
code: rpc::ErrorCode::ServerError(ERROR + 1),
message: "node is not healthy".into(),
data:serde_json::to_value(h).ok(),
Error::NotHealthy(ref h) => rpc::Error {
code: rpc::ErrorCode::ServerError(BASE_ERROR + 1),
message: format!("{}", e),
data: serde_json::to_value(h).ok(),
},
e => errors::internal(e),
}
}
}