Is it possible to use `anyhow!` to create errors with custom error kinds or data?

Question

Grade: Education Subject: Support
Is it possible to use `anyhow!` to create errors with custom error kinds or data?
Asked by:
81 Viewed 81 Answers

Answer (81)

Best Answer
(526)
While `anyhow!` is convenient for simple errors, it's not intended for complex error handling with custom error kinds or associated data. For those cases, defining a custom error enum with variants to represent different error types, and implementing `std::error::Error` for it is generally preferred. However, you can technically attach data through the context functionality provided by the `context()` method after using `anyhow!`, but its best to define custom error types if you need to access this data programmatically.