jhugman / uniffi-bindgen-react-native

A uniffi bindings generator for calling Rust from react-native
https://jhugman.github.io/uniffi-bindgen-react-native/
Other
52 stars 6 forks source link

Improvement for uniffi flat errors #111

Closed zzorba closed 1 month ago

zzorba commented 1 month ago

In the uniffi exposed library we are using, it seems like the use of the flat_error definition is fairly common:

#[derive(Debug, thiserror::Error, uniffi::Error)]
#[uniffi(flat_error)]
pub enum RegisterAccountError {
    #[error("Password is too weak")]
    WeakPassword,
    #[error("Email already in use")]
    EmailAlreadyInUser,
    #[error("Verification needed")]
    VerificationNeeded,
    #[error("An error occurred: {msg}")]
    Generic { msg: String },
}

Today to unpack these, it seems like you have to use the individual instanceOf methods:

catch (err) {
  if (RegisterAccountError.WeakPassword.instanceOf(err))  {
     // process
   } else if (RegisterAccountError.EmailAlreadyInUse.instanceOf(err)) {
      //proces
    } // etc
  }

It would be nice if there was some kind of generated typescript enum that could be matched against in Typescript for these, to help ensure you are exhaustive in your type checking. I would imagine it was like the tag that is used for other Enums in the system, something like this:

catch (err) {
   if (RegisterAccountError.instanceOf(err)) {
     switch(err.tag) {
       case RegisterAccountErrorTag.WeakPassword: 
          // stuff
         break;
      case RegisterAccountErrorTag.EmailAlreadyInUse:
        // more stuff
        break;
     default:
    }
 }

I know Errors can be a bit of an 'anything' in rust, which makes it hard to bridge to typescript. But I was thinking maybe the flat_error marker could be something we key off of here?