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
andrecover
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.