3 ms·
In Rust, you would implement From<ErrorA> and From<ErrorB> for a custom Error enum defined in your application/library. This will allow you to convert any Error
by Cyph0n 6y ago
In Rust, you would implement From<ErrorA> and From<ErrorB> for a custom Error enum defined in your application/library. This will allow you to convert any ErrorA or ErrorB into Error.
Then, you could simply return Result<Integer, Error> from your function, and the conversion would happen for you behind the scenes.
Of course, unless you track the original error types, you will lose some information. But it’s a very clean way to handle multiple error types within your library imo.
An example of how this works: https://doc.rust-lang.org/rust-by-example/error/multiple_error_types/wrap_error.html https://doc.rust-lang.org/rust-by-example/error/multiple_err...
- valenterry 6y ago> This will allow you to convert any ErrorA or ErrorB into Error. I chose my example for cases where I want to keep track of the different error cases. But even if I don't, I still have a _lot_ of overhead for converting them. Unfortunately Rust isn't a language that offers a solution to this problem so far. But there is an open RFC for it: https://github.com/rust-lang/rfcs/issues/294 https://github.com/rust-lang/rfcs/issues/294
- Cyph0n 6y agoI see. Yeah, this approach breaks down a bit if the error conversion logic is non-trivial.
- valenterry 6y agoActually, I'm wrong here, it's tagged union types not plain ones. But some commentary in there explains it better than me, so still helpful.