xmtp / libxmtp

LibXMTP is a shared library encapsulating the core functionality of the XMTP messaging protocol, such as cryptography, networking, and language bindings.
MIT License
42 stars 18 forks source link

Custom JS error classes/enum #104

Closed richardhuaaa closed 1 month ago

richardhuaaa commented 1 year ago

wasm_bindgen expects a JsValue to be returned from any function that can throw.

Currently, we handle this by returning JsError from all of our wasm bindings. This has the effect of auto-converting from Rust std::err::Error to JsError automatically via JsError::from, and then into JsValue via JsError::into.

The implementation of JsError::from is the JS equivalent of calling new Error(...) with the string generated from calling to_string() on the Rust error, which doesn't give consumers the opportunity to differentiate between different types of errors in code.

A workaround would be to define custom JS Error subclasses and import them into Rust, or define a special JS XMTPError type with an enum field and mappings from all known errors to this enum.

More info at https://github.com/rustwasm/wasm-bindgen/issues/1742#issuecomment-984149894

richardhuaaa commented 1 year ago

Another option is to define a trait TaggedError or similar, which expects a method/field called 'tag' which is a string, and implement it on all of our error types (with tag "unclassified" for anything else). And then from wasm, return a custom JS error type that has a 'tag' field and expect consuming clients to match based on that field.

richardhuaaa commented 1 year ago

Also, need to somehow get the error message from native errors from localStorage.getItem/setItem, and append them to the error string

insipx commented 1 month ago

closing in favor of https://github.com/xmtp/libxmtp/issues/557