title |
---|
Runtime Errors |
Runtime code should explicitly and gracefully handle all error cases, which is to say that runtime
code must be "non-throwing", or must never
"panic" to use Rust
terminology. A common idiom for writing non-throwing Rust code is to write functions that return
Result
types.
The Result
enum type possesses an Err
variant that allows a function to indicate that it failed
to execute successfully without needing to panic. Dispatchable calls in the FRAME system for runtime
development must return a
DispatchResult
type
that should be a
DispatchError
if the dispatchable function encountered an error.
Each FRAME pallet may define custom DispatchErrors by using
the decl_error!
macro.
// Errors inform users that something went wrong.
decl_error! {
pub enum Error for Module<T: Trait> {
/// Error names should be descriptive.
InvalidParameter,
/// Errors should have helpful documentation associated with them.
OutOfSpace,
}
}
In order to emit custom errors from a pallet, the pallet's module must configure the Error
type.
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
// Errors must be initialized if they are used by the pallet.
type Error = Error<T>;
/* --snip-- */
}
}
The
Pallet Template
demonstrates some ways to correctly handle errors in dispatchable functions. The FRAME Support
module also includes a helpful
ensure!
macro that can be
used to check pre-conditions and emit an errors if they are not met.
frame_support::ensure!(param < T::MaxVal::get(), Error::<T>::InvalidParameter);
- Learn more about the macros used in Substrate runtime development.