Handling errors and the Error interface
The Error
interface is a pretty small and simple interface:
type Error interface{ Error() string }
This interface is elegant because it's simple to make anything to satisfy it. Unfortunately, this also creates confusion for packages that need to take certain actions depending on the error received.
There are a number of ways to create errors in Go, this recipe will explore the creation of basic errors, errors that have assigned values or types, and of a custom error using a struct.
Getting ready
Configure your environment according to these steps:
- Download and install Go on your operating system from https://golang.org/doc/install, and configure your
GOPATH
environment variable. - Open a terminal/console application.
- Navigate to your
GOPATH/src
and create a project directory, for example,$GOPATH/src/github.com/yourusername/customrepo
.
All code will be run and modified from this directory.
- Optionally, install the latest tested version of the code using the
go...