casper_wasmi_core/
host_error.rs

1use core::fmt::{Debug, Display};
2use downcast_rs::{impl_downcast, DowncastSync};
3
4/// Trait that allows the host to return custom error.
5///
6/// It should be useful for representing custom traps,
7/// troubles at instantiation time or other host specific conditions.
8///
9/// Types that implement this trait can automatically be converted to `wasmi::Error` and `wasmi::Trap`
10/// and will be represented as a boxed `HostError`. You can then use the various methods on `wasmi::Error`
11/// to get your custom error type back
12///
13/// # Examples
14///
15/// ```rust
16/// use std::fmt;
17/// use casper_wasmi_core::{Trap, HostError};
18///
19/// #[derive(Debug)]
20/// struct MyError {
21///     code: u32,
22/// }
23///
24/// impl fmt::Display for MyError {
25///     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
26///         write!(f, "MyError, code={}", self.code)
27///     }
28/// }
29///
30/// impl HostError for MyError { }
31///
32/// fn failable_fn() -> Result<(), Trap> {
33///     let my_error = MyError { code: 1312 };
34///     // Note how you can just convert your errors to `wasmi::Error`
35///     Err(my_error.into())
36/// }
37///
38/// // Get a reference to the concrete error
39/// match failable_fn() {
40///     Err(Trap::Host(host_error)) => {
41///         let my_error: &MyError = host_error.downcast_ref::<MyError>().unwrap();
42///         assert_eq!(my_error.code, 1312);
43///     }
44///     _ => panic!(),
45/// }
46///
47/// // get the concrete error itself
48/// match failable_fn() {
49///     Err(err) => {
50///         let my_error = match err {
51///             Trap::Host(host_error) => host_error.downcast::<MyError>().unwrap(),
52///             unexpected => panic!("expected host error but found: {}", unexpected),
53///         };
54///         assert_eq!(my_error.code, 1312);
55///     }
56///     _ => panic!(),
57/// }
58///
59/// ```
60pub trait HostError: 'static + Display + Debug + DowncastSync {}
61impl_downcast!(HostError);