Coverage for wasmtime/_error.py: 95%
37 statements
« prev ^ index » next coverage.py v7.11.3, created at 2025-12-01 19:40 +0000
« prev ^ index » next coverage.py v7.11.3, created at 2025-12-01 19:40 +0000
1from ctypes import byref, POINTER, c_int
2from . import _ffi as ffi
3import ctypes
4from typing import Optional
5from wasmtime import Managed
8class WasmtimeError(Exception, Managed["ctypes._Pointer[ffi.wasmtime_error_t]"]):
9 __message: Optional[str]
11 def __init__(self, message: str):
12 self.__message = message
13 self._set_ptr(ffi.wasmtime_error_new(message.encode('utf-8')))
15 def _delete(self, ptr: "ctypes._Pointer[ffi.wasmtime_error_t]") -> None:
16 ffi.wasmtime_error_delete(ptr)
18 @classmethod
19 def _from_ptr(cls, ptr: "ctypes._Pointer[ffi.wasmtime_error_t]") -> 'WasmtimeError':
20 from . import _ffi as ffi
21 if not isinstance(ptr, POINTER(ffi.wasmtime_error_t)):
22 raise TypeError("wrong pointer type")
24 exit_code = c_int(0)
25 if ffi.wasmtime_error_exit_status(ptr, byref(exit_code)):
26 exit_trap: ExitTrap = ExitTrap.__new__(ExitTrap)
27 exit_trap._set_ptr(ptr)
28 exit_trap.__message = None
29 exit_trap.code = exit_code.value
30 return exit_trap
32 err: WasmtimeError = cls.__new__(cls)
33 err._set_ptr(ptr)
34 err.__message = None
35 return err
37 def __str__(self) -> str:
38 if self.__message:
39 return self.__message
40 message_vec = ffi.wasm_byte_vec_t()
41 ffi.wasmtime_error_message(self.ptr(), byref(message_vec))
42 message = ffi.to_str(message_vec)
43 ffi.wasm_byte_vec_delete(byref(message_vec))
44 return message
47class ExitTrap(WasmtimeError):
48 """
49 A special type of `WasmtimeError` which represents the process exiting via
50 WASI's `proc_exit` function call.
52 Whenever a WASI program exits via `proc_exit` a trap is raised, but the
53 trap will have this type instead of `WasmtimeError`, so you can catch just
54 this type instead of all traps (if desired). Exit traps have a `code`
55 associated with them which is the exit code provided at exit.
57 Note that `ExitTrap` is a subclass of `WasmtimeError`, so if you catch a
58 trap you'll also catch `ExitTrap`.
59 """
60 code: int
61 pass