unc_sdk/types/
error.rs

1/// Enables contract runtime to panic with the given type. Any error type used in conjunction
2/// with `#[handle_result]` has to implement this trait.
3///
4/// ```
5/// use unc_sdk::FunctionError;
6///
7/// enum Error {
8///     NotFound,
9///     Unexpected { message: String },
10/// }
11///
12/// impl FunctionError for Error {
13///     fn panic(&self) -> ! {
14///         match self {
15///             Error::NotFound =>
16///                 unc_sdk::env::panic_str("not found"),
17///             Error::Unexpected { message } =>
18///                 unc_sdk::env::panic_str(&format!("unexpected error: {}", message))
19///         }
20///     }
21/// }
22/// ```
23pub trait FunctionError {
24    fn panic(&self) -> !;
25}
26
27impl<T> FunctionError for T
28where
29    T: AsRef<str>,
30{
31    fn panic(&self) -> ! {
32        crate::env::panic_str(self.as_ref())
33    }
34}
35
36/// A simple type used in conjunction with [FunctionError] representing that the function should
37/// abort without a custom message.
38///
39/// ```
40/// use unc_sdk::{Abort, unc};
41///
42/// #[unc(contract_state)]
43/// #[derive(Default)]
44/// pub struct Contract;
45///
46/// #[unc]
47/// impl Contract {
48///     #[handle_result]
49///     pub fn foo(&self, text: &str) -> Result<String, Abort> {
50///         if text == "success" {
51///             Ok("success".to_string())
52///         } else {
53///             Err(Abort)
54///         }
55///     }
56/// }
57/// ```
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct Abort;
60
61impl FunctionError for Abort {
62    fn panic(&self) -> ! {
63        crate::env::abort()
64    }
65}