snarkvm_utilities/
error.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16#[cfg(feature = "std")]
17pub use std::error::Error;
18
19#[cfg(not(feature = "std"))]
20pub trait Error: core::fmt::Debug + core::fmt::Display {
21    fn source(&self) -> Option<&(dyn Error + 'static)> {
22        None
23    }
24}
25
26#[cfg(not(feature = "std"))]
27impl<'a, E: Error + 'a> From<E> for crate::Box<dyn Error + 'a> {
28    fn from(err: E) -> crate::Box<dyn Error + 'a> {
29        crate::Box::new(err)
30    }
31}
32
33#[cfg(not(feature = "std"))]
34impl<T: Error> Error for crate::Box<T> {}
35
36#[cfg(not(feature = "std"))]
37impl Error for crate::String {}
38
39#[cfg(not(feature = "std"))]
40impl Error for crate::io::Error {}
41
42/// This macro provides a VM runtime environment which will safely halt
43/// without producing logs that look like unexpected behavior.
44/// In debug mode, it prints to stderr using the format: "VM safely halted at <location>: <halt message>".
45#[macro_export]
46macro_rules! try_vm_runtime {
47    ($e:expr) => {{
48        use std::panic;
49
50        // Set a custom hook before calling catch_unwind to
51        // indicate that the panic was expected and handled.
52        panic::set_hook(Box::new(|e| {
53            let msg = e.to_string();
54            let msg = msg.split_ascii_whitespace().skip_while(|&word| word != "panicked").collect::<Vec<&str>>();
55            let mut msg = msg.join(" ");
56            msg = msg.replacen("panicked", "VM safely halted", 1);
57            #[cfg(debug_assertions)]
58            eprintln!("{msg}");
59        }));
60
61        // Perform the operation that may panic.
62        let result = panic::catch_unwind(panic::AssertUnwindSafe($e));
63
64        // Restore the standard panic hook.
65        let _ = panic::take_hook();
66
67        // Return the result, allowing regular error-handling.
68        result
69    }};
70}