7 Error management

 

This chapter covers

  • Understanding when to panic
  • Knowing when to wrap an error
  • Comparing error types and error values efficiently since Go 1.13
  • Handling errors idiomatically
  • Understanding how to ignore an error
  • Handling errors in defer calls

Error management is a fundamental aspect of building robust and observable applications, and it should be as important as any other part of a codebase. In Go, error management doesn’t rely on the traditional try/catch mechanism as most programming languages do. Instead, errors are returned as normal return values.

This chapter will cover the most common mistakes related to errors.

7.1 #48: Panicking

It’s pretty common for Go newcomers to be somewhat confused about error handling. In Go, errors are usually managed by functions or methods that return an error type as the last parameter. But some developers may find this approach surprising and be tempted to reproduce exception handling in languages such as Java or Python using panic and recover. So, let’s refresh our minds about the concept of panic and discuss when it’s considered appropriate or not to panic.

In Go, panic is a built-in function that stops the ordinary flow:

func main() {
    fmt.Println("a")
    panic("foo")
    fmt.Println("b")
}

This code prints a and then stops before printing b:

a
panic: foo
 
goroutine 1 [running]:
main.main()
        main.go:7 +0xb3

7.2  #49: Ignoring when to wrap an error

7.3 #50: Checking an error type inaccurately

7.4 #51: Checking an error value inaccurately

7.5 #52: Handling an error twice

7.6 #53: Not handling an error

7.7 #54: Not handling defer errors