Tech News
← Back to articles

Introduction to error handling strategies in Go

read original related products more articles

Error handling Introduction to error handling strategies in Go

Go's approach to error handling is based on two ideas:

Errors are an important part of an application's or library’s interface.

Failure is just one of several expected behaviors.

Thus, errors are values, just like any other values returned by a function. You should therefore pay close attention to how you create and handle them.

Some functions, like strings.Contains or strconv.FormatBool , can never fail. If a function can fail, it should return an additional value. If there's only one possible cause of failure, this value is a boolean:

value , ok := cache . Lookup ( key ) if ! ok { // key not found in cache }

If the failure can have multiple causes, the return value is of type error :

f , err := os . Open ( "/path/to/file" ) if err != nil { return nil , err }

The simplest way to create an error is by using fmt.Errorf (or errors.New if no formatting is needed):

... continue reading