7 Errors In Go

 

This chapter covers

  • The error type
  • Best practices for error handling in Go
  • Identifying different types of errors
  • Creating and using custom error types
  • Exceptional situations with panic and recover

In an ideal world, software would always function as intended, and programs left to their own devices would do their jobs flawlessly, forever. This is a nice dream, but even if your code is perfect in every way (which of course it is!), nothing runs in a vacuum. Even the simplest code can encounter unexpected conditions outside of its control, so it’s important to make sure your software can handle them when they happen.

Go aims to make error handling as straightforward and unremarkable as possible, favoring directness and explicitness over abstractions such as exception handling. It’s a prosaic (some might even say boring!) approach, but it also has a surprising flexibility, allowing the programmer to handle errors as simply or as deeply as they prefer.

In this chapter, you will explore how error handling is done the Go way, allowing you to write more resilient, robust software. To demonstrate the various ways to use errors, we will write a small Key-Value database.

7.1 Go Errors Are Values

7.2 The Go Error Type

7.3 Generating New Errors

7.4 Handling Errors

7.5 Logging Errors

7.6 Annotating Error Logs With Formatting

7.7 Sentinel Errors

7.8 Identifying Different Types of Errors

7.9 Creating a custom error type

7.10 Getting The Underlying Error With errors.As

7.11 An Unexpected Error Journey

7.12 Don’t Panic

7.12.1 Using Panic and Recover in your code

7.13 Summary