near_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/// Example:
5/// ```no_run
6/// use near_sdk::{FunctionError, near};
7///
8/// enum Error {
9/// NotFound,
10/// Unexpected { message: String },
11/// }
12///
13/// impl FunctionError for Error {
14/// fn panic(&self) -> ! {
15/// match self {
16/// Error::NotFound =>
17/// near_sdk::env::panic_str("not found"),
18/// Error::Unexpected { message } =>
19/// near_sdk::env::panic_str(&format!("unexpected error: {}", message))
20/// }
21/// }
22/// }
23///
24/// #[near(contract_state)]
25/// #[derive(Default)]
26/// pub struct Contract;
27///
28/// #[near]
29/// impl Contract {
30/// // if the Error does not implement FunctionError, the following will not compile with #[handle_result]
31/// #[handle_result]
32/// pub fn set(&self, value: String) -> Result<String, Error> {
33/// Err(Error::NotFound)
34/// }
35/// }
36/// ```
37pub trait FunctionError {
38 fn panic(&self) -> !;
39}
40
41impl<T> FunctionError for T
42where
43 T: AsRef<str>,
44{
45 fn panic(&self) -> ! {
46 crate::env::panic_str(self.as_ref())
47 }
48}
49
50/// A simple type used in conjunction with [FunctionError] representing that the function should
51/// abort without a custom message.
52///
53/// ```
54/// use near_sdk::{Abort, near};
55///
56/// #[near(contract_state)]
57/// #[derive(Default)]
58/// pub struct Contract;
59///
60/// #[near]
61/// impl Contract {
62/// #[handle_result]
63/// pub fn foo(&self, text: &str) -> Result<String, Abort> {
64/// if text == "success" {
65/// Ok("success".to_string())
66/// } else {
67/// Err(Abort)
68/// }
69/// }
70/// }
71/// ```
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct Abort;
74
75impl FunctionError for Abort {
76 fn panic(&self) -> ! {
77 crate::env::abort()
78 }
79}