Error handling. How to avoid using unnecessary error types in return value?


#1

Hi, everyone.
I’m confused about error handing in Rust.
For example:
I have two function. The first may end up with IO error or parse error. The second may end up with a parse error and out of bound one.
Now I know the way to handle this situation. I should create my own Error type.

For first function:
enum FirstFuncErrorType {
IoErr,
ParseErr,
}

For second function:
enum SecondFuncErrorType {
ParseErr,
OutOfBoundErr,
}

or a union enum of both

enum FirstFuncErrorType {
IoErr,
ParseErr,
OutOfBoundErr,
}

Is there a more convenient way in such situation.
In java I can add and remove exception types that a function throws. There is no need for special error type for each function or a super huge one for all cases in my crate.

void firstFunction() IOException, ParseException{
//…
}

void secondFunction() ParseException, OutOfBoundException{
//…
}

I know about good programming style and etc. I’m just curious about the possibility.
Thanks for any help.


#2

You may want to look into the error_chain crate. One of its purposes is to automatically generate the boilerplate needed to compose multiple error types in Rust. Here is a tutorial and some reference documentation.


#3

Apart from error_chain, which is the good style solution, you can also use Box<Error> (use std::error::Error) as your error type.
It’s roughly equivalent to Exception or Throwable in Java — it doesn’t say much about the identity of the error, but at least it’s compatible with all of them and you can use it if you don’t care about details.


#4

Another thing you can do is return a SimpleError in the functions you write, and map all the errors you get in the function with .map_err(|e| SimpleError::from(e)).