snarkvm_utilities/
error.rs

1// Copyright (c) 2019-2025 Provable Inc.
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
16pub use std::error::Error;
17
18/// This macro provides a VM runtime environment which will safely halt
19/// without producing logs that look like unexpected behavior.
20/// In debug mode, it prints to stderr using the format: "VM safely halted at {location}: {halt message}".
21#[macro_export]
22macro_rules! try_vm_runtime {
23    ($e:expr) => {{
24        use std::panic;
25
26        // Set a custom hook before calling catch_unwind to
27        // indicate that the panic was expected and handled.
28        panic::set_hook(Box::new(|e| {
29            let msg = e.to_string();
30            let msg = msg.split_ascii_whitespace().skip_while(|&word| word != "panicked").collect::<Vec<&str>>();
31            let mut msg = msg.join(" ");
32            msg = msg.replacen("panicked", "VM safely halted", 1);
33            #[cfg(debug_assertions)]
34            eprintln!("{msg}");
35        }));
36
37        // Perform the operation that may panic.
38        let result = panic::catch_unwind(panic::AssertUnwindSafe($e));
39
40        // Restore the standard panic hook.
41        let _ = panic::take_hook();
42
43        // Return the result, allowing regular error-handling.
44        result
45    }};
46}