fzyzcjy / flutter_rust_bridge

Flutter/Dart <-> Rust binding generator, feature-rich, but seamless and simple.
https://fzyzcjy.github.io/flutter_rust_bridge/
MIT License
4.29k stars 301 forks source link

[experimental-feature] Return custom Rust errors #2369

Closed oo-work closed 2 weeks ago

oo-work commented 4 weeks ago

Now there is an Error in a third-party crate, which may be like this.

#[derive(Debug)]
pub enum CustomError {
    ConnectionError(Box<dyn std::error::Error + Send + Sync>),
    Io(std::io::Error),
    Other(Box<dyn std::error::Error + Send + Sync>),
    EOF,
}

flutter_rust_bridge.yaml

rust_input: crate::api,crate-name::error

When returning a Result<(), CustomError), Dart uses print(e.runtimeType); to print out CustomErrorImpl.

pub fn foo() -> Result<(), CustomError>{
    ...
}
try {
    await foo();
} catch(e) {
    print(e.runtimeType);
}

I want it to be a CustomError and have access to the type in the enum and call toString().

But dart generates such code, and the Exception type is not CustomError.

abstract class CustomError implements RustOpaqueInterface {
}
welcome[bot] commented 4 weeks ago

Hi! Thanks for opening your first issue here! :smile:

fzyzcjy commented 4 weeks ago

Here your CustomError should auto implements FrbException but indeed it does not.

Since you are using the experimental feature of auto scanning a whole third party crate, I guess this may be the cause.

A workaround may be, could you please try to have your CustomError in your main crate (instead of third party crate), or use the manual way of mirroring the 3rd party crate?

oo-work commented 3 weeks ago

After I use mirror, Rust struct can be translated into FrbException. But Rust enum cannot be used as FrbException, it will always be translated into RustOpaqueInterface

fzyzcjy commented 3 weeks ago

https://cjycode.com/flutter_rust_bridge/guides/third-party/manual/external-types#example Seems that mirror is:

Enums with struct variants are not yet supported

A workaround may be, create your own enum in first party package (and convert it between the 3rd party one).

oo-work commented 2 weeks ago

I tried changing the enum to a normal struct and it working.

fzyzcjy commented 2 weeks ago

Happy to see that!

fzyzcjy commented 2 weeks ago

Close since this seems to be solved, but feel free to reopen if you have any questions!

github-actions[bot] commented 3 days ago

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new issue.