3 ms·
If you are writing your own library then your best bet is to define your own Error enum in each module. Below each Error enum write a bunch of From trait implem
by davidhyde 5y ago
If you are writing your own library then your best bet is to define your own Error enum in each module. Below each Error enum write a bunch of From trait implementations to convert errors into a custom variant in your Error enum. This allows you to use the "?" operator to "bubble" errors up through your library and build some sort of useful printable error tree. Don't used boxed errors and don't use std:io:Error for your own custom purposes. Doing things this way will mean that consumers of your library will not be bound to use some error handling library that they may not want to use. It is also very fast.
If this is not a library then feel free to use any number of error handling helper libraries out there. It would be unfair to single one of them out. However, once I got the hang of writing my on custom errors I ended up using them for my binary applications too.
- da39a3ee 5y agoThanks, that's very helpful and may well be the encouragement I apparently needed! It is a standalone CLI application but it might want to offer a library in the future. And in any case I am attracted to following your suggestion regarding custom enums, partly because it seems more likely to dispel my lack of understanding of the topic.
- davidhyde 5y agoCheers! It's a daunting topic with many different ways of doing things and it is difficult to find reading material on the topic of idiomatic error handling. I just read through a lot of popular code bases and picked out what I liked. I found that using custom errors was the simplest approach for me albeit a little verbose.
- shepmaster 5y ago> If you are writing your own library then your best bet is to define your own Error enum in each module This is exactly the path that my SNAFU library takes. It’s a procedural macro attached to an enum that generates the From, Display and Error traits for you. This way, consumers of your code don’t need to know anything beyond the fact that you implement Error and any inherent public methods or traits you choose to expose. The implementation provided by SNAFU is internal to your code. https://docs.rs/snafu/0.6.10/snafu/ https://docs.rs/snafu/0.6.10/snafu/