4 Handling errors and panics

 

This chapter covers

  • Learning idiomatic error handling in Go
  • Returning meaningful data with errors
  • Adding custom error types the Go way
  • Generating and working with panics
  • Transforming panics into errors
  • Working with panics on goroutines

As Robert Burns famously stated in his poem “To a Mouse,” “The best laid schemes o’ Mice an’ Men/Gang aft agley.” Our best plans often still go wrong. No other profession knows this truth as thoroughly as software development. This chapter focuses on handling situations when things go awry.

Go distinguishes between errors and panics—two types of bad things that can happen during program execution. An error indicates that a particular task couldn’t be completed successfully. A panic indicates that a severe event occurred, probably as a result of a programmer error or unexpected environment state, and the program must exit as soon as possible. This chapter presents a thorough look at each category.

4.1 Error handling

4.1.1 Nil best practices

4.1.2 Custom error types

4.1.3 Error variables

4.2 Wrapping errors

4.3 The panic system

4.3.1 Differentiating panics from errors

4.3.2 Working with panics

4.3.3 Recovering from panics

4.3.4 Capturing panics with defer

4.3.5 Handling panics on goroutines

Summary