xref: /wasmtime-44.0.1/crates/c-api/src/error.rs (revision bd374fd6)
1 use crate::{wasm_name_t, wasm_trap_t};
2 use anyhow::{anyhow, Error, Result};
3 use wasmtime::Trap;
4 
5 #[repr(C)]
6 pub struct wasmtime_error_t {
7     error: Error,
8 }
9 
10 wasmtime_c_api_macros::declare_own!(wasmtime_error_t);
11 
12 impl wasmtime_error_t {
13     pub(crate) fn to_trap(&self) -> Box<wasm_trap_t> {
14         Box::new(wasm_trap_t::new(Trap::new(format!("{:?}", self.error))))
15     }
16 }
17 
18 impl From<Error> for wasmtime_error_t {
19     fn from(error: Error) -> wasmtime_error_t {
20         wasmtime_error_t { error }
21     }
22 }
23 
24 pub(crate) fn handle_result<T>(
25     result: Result<T>,
26     ok: impl FnOnce(T),
27 ) -> Option<Box<wasmtime_error_t>> {
28     match result {
29         Ok(value) => {
30             ok(value);
31             None
32         }
33         Err(error) => Some(Box::new(wasmtime_error_t { error })),
34     }
35 }
36 
37 pub(crate) fn bad_utf8() -> Option<Box<wasmtime_error_t>> {
38     Some(Box::new(wasmtime_error_t {
39         error: anyhow!("input was not valid utf-8"),
40     }))
41 }
42 
43 #[no_mangle]
44 pub extern "C" fn wasmtime_error_message(error: &wasmtime_error_t, message: &mut wasm_name_t) {
45     message.set_buffer(format!("{:?}", error.error).into_bytes());
46 }
47