Why Use Structured Errors in Rust Applications?

https://news.ycombinator.com/rss Hits: 10
Summary

Why Use Structured Errors in Rust Applications?TL;DR I prefer thiserror enums over anyhow, even for application code that simply propagates errors. Custom error types require additional effort, but make the code easier to reason about and maintain down the road.“Using thiserror for libraries and anyhow for applications” In 2025, this is the conventional error handling practice in the Rust community. Let’s quickly recap the main ideas:Libraries should expose error types that provide as much information as possible. This allows the callers to detect and handle specific error conditions. A specific error code is more useful than “Oops, something went wrong”. Structured error types facilitate statically-checked pattern matching, which is more reliable than runtime reflection, downcasting, or regex-matching an error message. They also provide nice autogenerated docs, which is very important for libraries.Unfortunately, propagating structured errors in Rust is associated with the boilerplate of manually writing out wrapper error types, their impls and conversions. thiserror removes the boilerplate around implementing Display , Error and From for your error types. Using it is a no-brainer for libraries that can “afford” proc macro dependencies. Although, you still need to define and annotate the wrapper types themselves, which there are usually plenty.End applications often don’t care about the specific cause of an error and simply propagate errors up the stack until they reach some kind of a “catch-all” point. For this use case, even thiserror-assisted error types are often considered too cumbersome and not worth it.Instead, application developers commonly use anyhow . It provides a “universal” dynamic error type, along with helper methods that make dealing with it even easier than returning a string. If you google “error handling in Rust”, the typical introductory posts are going to start with the basics of panic, Option and Result, then explain these two libraries, give...

First seen: 2025-06-01 09:30

Last seen: 2025-06-01 18:32