7 From panic to result: Error handling
This chapter covers
- Understanding the difference between pure and impure functions
- Understanding the downsides of breaking control flow
- Using
Result
for better error handling - Writing macros to manipulate function signatures and return values
- Mutating the received
TokenStream
as an alternative to creating a new one - Creating better error messages with
syn::Error
orproc_macro_error
Until now, most of our code has focused on structs and enums, with very basic error handling. All of that changes right now! In this chapter, we will manipulate functions, changing panics into Result
s, which is a better and more idiomatic way of handling errors in Rust. This is a useful segue into seeing how we can manipulate functions with an attribute macro. We will also use this code to explore better ways of returning errors to the user—because panicking works, but the error just points to the macro invocation, making usage harder than it needs to be. But first, as a general introduction to this chapter’s macro, let’s talk about the problem with exceptions and possible alternatives.