Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

chore/error: remove from str conversion and add deprecation notificat… #7472

Merged
39 commits merged into from
Nov 27, 2020
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
8467f4a
chore/error: remove from str conversion and add deprecation notificat…
Oct 30, 2020
91744cd
fixup changes
Nov 3, 2020
c1085eb
fix test looking for gone ::Msg variant
Nov 3, 2020
524ee71
another test fix
Nov 4, 2020
2a09d3c
one is duplicate, the other is not, so duplicates reported are n-1
Nov 4, 2020
dbbd20f
darn spaces
drahnr Nov 10, 2020
8d021f0
remove pointless doc comments of error variants without any value
Nov 10, 2020
311a58f
Merge remote-tracking branch 'origin/master' into bernhard-error-chore
Nov 11, 2020
8b3f12b
low hanging fruits (for a tall person)
Nov 13, 2020
2dbc971
moar error type variants
Nov 14, 2020
3e94fa6
avoid the storage modules for now
Nov 17, 2020
666dd5f
chore remove pointless error generic
Nov 17, 2020
69e849b
fix test for mocks, add a bunch of non_exhaustive
Nov 17, 2020
d54cb37
max line width
Nov 17, 2020
10a2278
Merge remote-tracking branch 'origin/master' into bernhard-error-chore
Nov 18, 2020
66b6989
test fixes due to error changes
Nov 20, 2020
49fe444
fin
Nov 25, 2020
2b5f9d7
Merge remote-tracking branch 'origin/master' into bernhard-error-chore
Nov 25, 2020
ff81007
error outputs... again
Nov 25, 2020
13ba47b
undo stderr adjustments
Nov 26, 2020
3dda02d
Update client/consensus/slots/src/lib.rs
drahnr Nov 26, 2020
eb7805b
remove closure clutter
drahnr Nov 26, 2020
536f11e
more error types
Nov 26, 2020
bc40955
introduce ApiError
Nov 26, 2020
31f0259
extract Mock error
Nov 26, 2020
717ec7d
ApiError refactor
Nov 26, 2020
b4c1348
even more error types
Nov 26, 2020
cc2353d
the last for now
Nov 26, 2020
1d364ac
chore unused deps
Nov 26, 2020
56a0b2d
another extraction
Nov 26, 2020
c080594
reduce should panic, due to extended error messages
Nov 26, 2020
077301e
error test happiness
Nov 26, 2020
0983c88
shift error lines by one
Nov 27, 2020
0e9d696
doc tests
Nov 27, 2020
4b752b0
Merge remote-tracking branch 'origin/master' into bernhard-error-chore
Nov 27, 2020
35d2814
white space
drahnr Nov 27, 2020
13810eb
Into -> From
drahnr Nov 27, 2020
6df60d0
remove pointless codec
drahnr Nov 27, 2020
d0c0d24
avoid pointless self import
drahnr Nov 27, 2020
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
12 changes: 4 additions & 8 deletions client/cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,6 @@ pub enum Error {
/// Invalid listen multiaddress
#[error("Invalid listen multiaddress")]
InvalidListenMultiaddress,
/// Application specific error chain sequence forwarder.
#[error(transparent)]
Application(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
/// URI error.
#[error("Invalid URI; expecting either a secret URI or a public URI.")]
InvalidUri(crypto::PublicError),
Expand Down Expand Up @@ -79,10 +76,9 @@ pub enum Error {
/// Bytes are not decodable when interpreted as hexadecimal string.
#[error("Invalid hex base data")]
HexDataConversion(#[from] hex::FromHexError),
/// Shortcut type to specify types on the fly, discouraged.
#[deprecated = "Use `Forwarded` with an error type instead."]
#[error("Other: {0}")]
Other(String),
/// Application specific error chain sequence forwarder.
#[error(transparent)]
Application(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),
}

impl std::convert::From<&str> for Error {
Expand All @@ -93,7 +89,7 @@ impl std::convert::From<&str> for Error {

impl std::convert::From<String> for Error {
fn from(s: String) -> Error {
Error::Input(s.to_string())
Error::Input(s)
}
}

Expand Down
21 changes: 6 additions & 15 deletions client/service/src/client/wasm_override.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,16 +119,13 @@ where
/// Scrapes a folder for WASM runtimes.
/// Returns a hashmap of the runtime version and wasm runtime code.
fn scrape_overrides(dir: &Path, executor: &E) -> Result<HashMap<u32, WasmBlob>> {

let handle_err = |e: std::io::Error | -> sp_blockchain::Error {
sp_blockchain::Error::Msg(format!("{}", e.to_string()))
sp_blockchain::Error::WasmOverrideIo(dir.to_owned(), e)
drahnr marked this conversation as resolved.
Show resolved Hide resolved
};

if !dir.is_dir() {
return Err(sp_blockchain::Error::Msg(format!(
"Overwriting WASM requires a directory where \
local WASM is stored. {:?} is not a directory",
dir,
)));
return Err(sp_blockchain::Error::WasmOverrideNotADirectory(dir.to_owned()));
}

let mut overrides = HashMap::new();
Expand All @@ -149,9 +146,7 @@ where
}

if !duplicates.is_empty() {
let duplicate_file_list = duplicates.join("\n");
let msg = format!("Duplicate WASM Runtimes found: \n{}\n", duplicate_file_list);
return Err(sp_blockchain::Error::Msg(msg));
return Err(sp_blockchain::Error::DuplicateWasmRuntime(duplicates));
}

Ok(overrides)
Expand Down Expand Up @@ -238,12 +233,8 @@ mod tests {
match scraped {
Err(e) => {
match e {
sp_blockchain::Error::Msg(msg) => {
let is_match = msg
.matches("Duplicate WASM Runtimes found")
.map(ToString::to_string)
.collect::<Vec<String>>();
assert!(is_match.len() >= 1)
sp_blockchain::Error::DuplicateWasmRuntime(duplicates) => {
assert_eq!(duplicates.len(), 1);
ordian marked this conversation as resolved.
Show resolved Hide resolved
},
_ => panic!("Test should end with Msg Error Variant")
}
Expand Down
14 changes: 5 additions & 9 deletions client/sync-state-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,13 @@ impl<TBl, TCl> SyncStateRpcHandler<TBl, TCl>
fn build_sync_state(&self) -> Result<sc_chain_spec::LightSyncState<TBl>, sp_blockchain::Error> {
let finalized_hash = self.client.info().finalized_hash;
let finalized_header = self.client.header(BlockId::Hash(finalized_hash))?
.ok_or_else(|| sp_blockchain::Error::Msg(
format!("Failed to get the header for block {:?}", finalized_hash)
))?;
.ok_or_else(|| sp_blockchain::Error::MissingHashInHeader(finalized_hash.to_string()))?;

let finalized_block_weight = sc_consensus_babe::aux_schema::load_block_weight(
&*self.client,
finalized_hash,
)?
.ok_or_else(|| sp_blockchain::Error::Msg(
format!("Failed to load the block weight for block {:?}", finalized_hash)
))?;
&*self.client,
finalized_hash,
)?
.ok_or_else(|| sp_blockchain::Error::MissingBlockWeightInHeader(finalized_hash.to_string()))?;
drahnr marked this conversation as resolved.
Show resolved Hide resolved

Ok(sc_chain_spec::LightSyncState {
finalized_block_header: finalized_header,
Expand Down
4 changes: 2 additions & 2 deletions primitives/blockchain/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ pub trait Backend<Block: BlockT>: HeaderBackend<Block> + HeaderMetadata<Block, E
if let Some(max_number) = maybe_max_number {
loop {
let current_header = self.header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| Error::from(format!("failed to get header for hash {}", current_hash)))?;
.ok_or_else(|| Error::MissingHashInHeader(current_hash.to_string()))?;
drahnr marked this conversation as resolved.
Show resolved Hide resolved

if current_header.number() <= &max_number {
best_hash = current_header.hash();
Expand All @@ -191,7 +191,7 @@ pub trait Backend<Block: BlockT>: HeaderBackend<Block> + HeaderMetadata<Block, E
}

let current_header = self.header(BlockId::Hash(current_hash.clone()))?
.ok_or_else(|| Error::from(format!("failed to get header for hash {}", current_hash)))?;
.ok_or_else(|| Error::MissingHashInHeader(current_hash.to_string()))?;

// stop search in this chain once we go below the target's block number
if current_header.number() < target_header.number() {
Expand Down
80 changes: 66 additions & 14 deletions primitives/blockchain/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

//! Substrate client possible errors.

use std::{self, result};
use std::{self, result, path::PathBuf};
use sp_state_machine;
use sp_runtime::transaction_validity::TransactionValidityError;
use sp_consensus;
Expand All @@ -35,110 +35,150 @@ pub enum ApplyExtrinsicFailed {
/// unappliable onto the current block.
#[error("Extrinsic is not valid: {0:?}")]
Validity(#[from] TransactionValidityError),

/// This is used for miscellaneous errors that can be represented by string and not handleable.
///
/// This will become obsolete with complete migration to v4 APIs.
#[deprecated(note = "Introduce more typed error variants as needed")]
drahnr marked this conversation as resolved.
Show resolved Hide resolved
#[error("Extrinsic failed: {0}")]
Msg(String),
}

/// Substrate Client error
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
drahnr marked this conversation as resolved.
Show resolved Hide resolved
pub enum Error {
/// Consensus Error
#[error(transparent)]
Consensus(#[from] sp_consensus::Error),

/// Backend error.
#[error("Backend error: {0}")]
Backend(String),

/// Unknown block.
#[error("UnknownBlock: {0}")]
UnknownBlock(String),

/// The `apply_extrinsic` is not valid due to the given `TransactionValidityError`.
#[error(transparent)]
ApplyExtrinsicFailed(#[from] ApplyExtrinsicFailed),

/// Execution error.
// `inner` cannot be made member, since it lacks `std::error::Error` trait bounds.
#[error("Execution failed: {0:?}")]
Execution(Box<dyn sp_state_machine::Error>),

/// Blockchain error.
#[error("Blockchain")]
Blockchain(#[source] Box<Error>),

/// Invalid authorities set received from the runtime.
#[error("Current state of blockchain has invalid authorities set")]
InvalidAuthoritiesSet,

/// Could not get runtime version.
#[error("Failed to get runtime version: {0}")]
VersionInvalid(String),

/// Genesis config is invalid.
#[error("Genesis config provided is invalid")]
GenesisInvalid,

/// Error decoding header justification.
#[error("error decoding justification for header")]
JustificationDecode,

/// Justification for header is correctly encoded, but invalid.
#[error("bad justification for header: {0}")]
BadJustification(String),

/// Not available on light client.
#[error("This method is not currently available when running in light client mode")]
NotAvailableOnLightClient,

/// Invalid remote CHT-based proof.
#[error("Remote node has responded with invalid header proof")]
InvalidCHTProof,

/// Remote fetch has been cancelled.
#[error("Remote data fetch has been cancelled")]
RemoteFetchCancelled,

/// Remote fetch has been failed.
#[error("Remote data fetch has been failed")]
RemoteFetchFailed,

/// Error decoding call result.
#[error("Error decoding call result of {0}")]
CallResultDecode(&'static str, #[source] CodecError),

/// Error converting a parameter between runtime and node.
#[error("Error converting `{0}` between runtime and node")]
RuntimeParamConversion(String),

/// Changes tries are not supported.
#[error("Changes tries are not supported by the runtime")]
ChangesTriesNotSupported,

/// Error reading changes tries configuration.
#[error("Error reading changes tries configuration")]
ErrorReadingChangesTriesConfig,

/// Key changes query has failed.
#[error("Failed to check changes proof: {0}")]
ChangesTrieAccessFailed(String),

/// Last finalized block not parent of current.
#[error("Did not finalize blocks in sequential order.")]
NonSequentialFinalization(String),

/// Safety violation: new best block not descendent of last finalized.
#[error("Potential long-range attack: block not in finalized chain.")]
NotInFinalizedChain,

/// Hash that is required for building CHT is missing.
#[error("Failed to get hash of block for building CHT")]
MissingHashRequiredForCHT,

/// Invalid calculated state root on block import.
#[error("Calculated state root does not match.")]
InvalidStateRoot,

/// Incomplete block import pipeline.
#[error("Incomplete block import pipeline.")]
IncompletePipeline,

/// Transaction pool initizliation is not complete.
#[error("Transaction pool not ready for block production.")]
TransactionPoolNotReady,

/// Database yielded an error.
#[error("Database")]
DatabaseError(#[from] sp_database::error::DatabaseError),
/// A convenience variant for String
#[error("{0}")]
Msg(String),
}

impl<'a> From<&'a str> for Error {
fn from(s: &'a str) -> Self {
Error::Msg(s.into())
}
}
#[error("Failed to get header for hash {0}")]
MissingHashInHeader(String),
drahnr marked this conversation as resolved.
Show resolved Hide resolved

impl From<String> for Error {
fn from(s: String) -> Self {
Error::Msg(s)
}
#[error("Failed to load the block weight for block {0}")]
MissingBlockWeightInHeader(String),

#[error("WASM override IO error")]
WasmOverrideIo(PathBuf, #[source] std::io::Error),

#[error("Overwriting WASM requires a directory where local \
WASM is stored. {} is not a directory", .0.display())]
WasmOverrideNotADirectory(PathBuf),

#[error("Duplicate WASM Runtimes found: \n{}\n", .0.join("\n") )]
DuplicateWasmRuntime(Vec<String>),
drahnr marked this conversation as resolved.
Show resolved Hide resolved

#[error(transparent)]
Foreign(#[from] Box<dyn std::error::Error + Send + Sync + 'static>),

/// Should be avoided if possible, use `Foreign` instead.
drahnr marked this conversation as resolved.
Show resolved Hide resolved
#[error("{0}")]
Msg(String),
}

impl From<Box<dyn sp_state_machine::Error + Send + Sync>> for Error {
Expand All @@ -153,6 +193,18 @@ impl From<Box<dyn sp_state_machine::Error>> for Error {
}
}

impl From<String> for Error {
fn from(msg: String) -> Self {
Self::Msg(msg)
}
}
impl From<&str> for Error {
fn from(msg: &str) -> Self {
Self::Msg(msg.to_owned())
}
}


impl Error {
/// Chain a blockchain error.
pub fn from_blockchain(e: Box<Error>) -> Self {
Expand Down