title |
---|
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 a DispatchError
by:
- using
the
decl_error!
macro (FRAME v1) or; - the
#[pallet::error]
macro (FRAME v2).
// FRAME v1.
// Errors inform users that something went wrong.
decl_error! {
pub enum Error for Module<T: Config> {
/// Error names should be descriptive.
InvalidParameter,
/// Errors should have helpful documentation associated with them.
OutOfSpace,
}
}
// FRAME v2.
#[pallet::error]
pub enum Error<T> {
/// Error names should be descriptive.
InvalidParameter,
/// Errors should have helpful documentation associated with them.
OutOfSpace,
}
Note: In FRAME v1, in order to emit custom errors from a pallet, the pallet must configure the
Error
type indecl_module!
. See the Rust docs for more details.
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.