On dealing with propagating errors

Quick check to see if I'm on the right path.

I have a struct holding some information, which I want to convert from and into a file using serde (similar to this). For that I've created a few convenience methods to do the saving and loading.

These methods have various points that could fail (most importantly converting a file/struct to a string and serializing/deserializing) which I want to return an error for rather than outright panicking, so tldr returning a Result.

For those cases, would thiserror be the go-to method? In the future when I add more places where I'd want to do the same, would it be bad practice to group every error of every place under a single enum rather than having some granularity?

At some point the enum gets too big to be useful, and too coupled to all the different libraries you might be using.

The general advice is that error-handling is different between libraries and binaries.

For "libraries", the enum can be better as it's more important to show exactly which kinds of things can happen and it's more reasonable for a caller to want to exhaustively match.

For "binaries", a Box<dyn Error>-based approach like Anyhow — Rust library // Lib.rs can be better as it's lower-friction. At the most obvious, returning from main doesn't need to have a big detailed enum, since it's not like anyone will care for the detail. And it still allows downcasting checks for the usually-few errors you want to check for.

Of course, this isn't all-or-nothing. It's very plausible that you'd have some modules that are more library-like and which are consumed by more binary-like modules.

Yep, this seems like what I'd need. Mix of both it is!

From a practical standpoint, I've found that most executable projects I write are the "long lived" variety, like games, GUI apps, web servers, etc. For these cases, main doesn't usually return an error type, and error handling with enums and thiserror tends to still be preferable over trait objects.

But depending on personal preference, you might still find the lower friction with anyhow to your liking.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.