Register an error class so it can be recognized by the ffi error handler. Parameters ---------- name_or_cls The name of the error class. cls The class to register. Returns ------- fregister Register function if f is not specified. Examples
(
name_or_cls: str | type | None = None,
cls: type | None = None,
)
| 203 | |
| 204 | |
| 205 | def register_error( |
| 206 | name_or_cls: str | type | None = None, |
| 207 | cls: type | None = None, |
| 208 | ) -> Any: |
| 209 | """Register an error class so it can be recognized by the ffi error handler. |
| 210 | |
| 211 | Parameters |
| 212 | ---------- |
| 213 | name_or_cls |
| 214 | The name of the error class. |
| 215 | |
| 216 | cls |
| 217 | The class to register. |
| 218 | |
| 219 | Returns |
| 220 | ------- |
| 221 | fregister |
| 222 | Register function if f is not specified. |
| 223 | |
| 224 | Examples |
| 225 | -------- |
| 226 | .. code-block:: python |
| 227 | |
| 228 | import tvm_ffi |
| 229 | |
| 230 | |
| 231 | # Register a custom Python exception so tvm_ffi.Error maps to it |
| 232 | @tvm_ffi.error.register_error |
| 233 | class MyError(RuntimeError): |
| 234 | pass |
| 235 | |
| 236 | |
| 237 | # Convert a Python exception to an FFI Error and back |
| 238 | ffi_err = tvm_ffi.convert(MyError("boom")) |
| 239 | py_err = ffi_err.py_error() |
| 240 | assert isinstance(py_err, MyError) |
| 241 | |
| 242 | """ |
| 243 | if isinstance(name_or_cls, type): |
| 244 | cls = name_or_cls |
| 245 | name_or_cls = cls.__name__ |
| 246 | |
| 247 | def register(mycls: type) -> type: |
| 248 | """Register the error class name with the FFI core.""" |
| 249 | err_name = name_or_cls if isinstance(name_or_cls, str) else mycls.__name__ |
| 250 | core.ERROR_NAME_TO_TYPE[err_name] = mycls |
| 251 | core.ERROR_TYPE_TO_NAME[mycls] = err_name |
| 252 | return mycls |
| 253 | |
| 254 | if cls is None: |
| 255 | return register |
| 256 | return register(cls) |
| 257 | |
| 258 | |
| 259 | register_error("RuntimeError", RuntimeError) |