near_sdk/types/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/// Enables contract runtime to panic with the given type. Any error type used in conjunction
/// with `#[handle_result]` has to implement this trait.
///
/// Example:
/// ```no_run
/// use near_sdk::{FunctionError, near};
///
/// enum Error {
///     NotFound,
///     Unexpected { message: String },
/// }
///
/// impl FunctionError for Error {
///     fn panic(&self) -> ! {
///         match self {
///             Error::NotFound =>
///                 near_sdk::env::panic_str("not found"),
///             Error::Unexpected { message } =>
///                 near_sdk::env::panic_str(&format!("unexpected error: {}", message))
///         }
///     }
/// }
///
/// #[near(contract_state)]
/// #[derive(Default)]
/// pub struct Contract;
///
/// #[near]
/// impl Contract {
///     // if the Error does not implement FunctionError, the following will not compile with #[handle_result]
///     #[handle_result]
///     pub fn set(&self, value: String) -> Result<String, Error> {
///         Err(Error::NotFound)
///     }
/// }
/// ```
pub trait FunctionError {
    fn panic(&self) -> !;
}

impl<T> FunctionError for T
where
    T: AsRef<str>,
{
    fn panic(&self) -> ! {
        crate::env::panic_str(self.as_ref())
    }
}

/// A simple type used in conjunction with [FunctionError] representing that the function should
/// abort without a custom message.
///
/// ```
/// use near_sdk::{Abort, near};
///
/// #[near(contract_state)]
/// #[derive(Default)]
/// pub struct Contract;
///
/// #[near]
/// impl Contract {
///     #[handle_result]
///     pub fn foo(&self, text: &str) -> Result<String, Abort> {
///         if text == "success" {
///             Ok("success".to_string())
///         } else {
///             Err(Abort)
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Abort;

impl FunctionError for Abort {
    fn panic(&self) -> ! {
        crate::env::abort()
    }
}