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 or proc_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 Results, 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.

7.1 Errors and control flow

7.2 Pure and impure functions

7.3 Alternatives to exceptions

7.4 Rust’s Result and panics

7.5 Setup of the panic project

7.6 Mutable or immutable returns

7.7 Getting results

7.8 Don’t panic

7.8.1 Changing the panic into a Result

7.8.2 Debugging observations

7.9 Error-handling flavors

7.9.1 Using syn for error handling

7.9.2 Using proc_macro_error for error handling

7.9.3 Deciding between syn and proc_macro_error

7.10 From the real world

7.11 Exercises

Summary