Runtime 错误
Runtime代码应该显式且优雅地处理所有错误情况,也就是说runtime代码 必须是“不抛出”的,用Rust术语来讲,就是决不能"panic" 。 A common idiom for writing non-throwing Rust code is to write functions that return Result
types. Result
枚举类型具有一个名为 Err
的变量,该变量可让函数传达执行失败的信息,以避免程序“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.
每个FRAME pallet都可以使用decl_error!
宏来自定义 DispatchError的内容。
// 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,
}
}
为了能在pallet中触发自定义错误,pallet的module部分必须要配置Error
类型。
decl_module! {
pub struct Module<T: Config> for enum Call where origin: T::Origin {
// Errors must be initialized if they are used by the pallet.
type Error = Error<T>;
/* --snip-- */
}
}
Pallet 模版演示了如何正确处理可调用函数内错误的一些方法。 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);
后续步骤
进一步学习
- 了解更多关于Substrate runtime开发中使用的 宏的信息。