Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are all the different error types in Rust?

I'm learning Rust and can't find a list of all error types. When a function is returning a Result, does the standard library have a group of predefined errors available for use?

I know custom error types can be made in Rust, is that the solution? Make all custom errors types?

like image 539
Josh R Avatar asked Dec 04 '25 13:12

Josh R


2 Answers

It's not well defined what "an error type" would mean, so no, there is no global list of errors.

If you mean "is there a list of all the types that are used as Result::Err, the answer is still no. There are methods like slice::binary_search which return Result<usize, usize>. Is usize to be considered an error type? What if a Result::Err is constructed entirely inside of a function and never leaves it; is that type considered an error type? What about a generic type that contains a Result<i32, E>; should any concrete E be called an error type?

If you mean "is there a list of all the types that implement std::error::Error, then the answer is "kind of". See How can I get a list of structs that implement a particular trait in Rust? for details.

does the standard library have a group of predefined errors

Yes.

available for use

Sometimes. io::Error allows you to construct your own error value, but num::ParseIntError does not.

is that the solution? Make all custom errors types?

Generally, yes.

See also:

  • How do you define custom `Error` types in Rust?
like image 57
Shepmaster Avatar answered Dec 07 '25 13:12

Shepmaster


Result types are often aliased in the standard library. If you see a function in the standard library documentation, you can click on Result, which should lead you to the aliased type (e.g. std::io::Result) You can then see which kind of Error is used in the Result.

The documentation also has a list of all enums and structs in the standard library that implement the Error trait.

like image 38
riginding Avatar answered Dec 07 '25 14:12

riginding