Error Handing with Go-Lang

Kassim Damilola
Nov 4 · 2 min read

Go has a unique approach to handling errors. unlike most programming languages, errors in Go are values it can be returned, declared, manipulated like any other value. There are no special syntax, library or class for errors, errors are treated as normal operations, examined to determine what should occur, or be returned.

Creating errors

Since errors are like any other value it can be created using the New() method from the errors package.

import (
"errors"
"fmt"
)

func main() {
err := errors.New("You caused this")
fmt.Println("Oops ", err)
}

Error operations

Usually errors are not created only to be retured. Errors should actually be retured when something goes wrong

oops.png

The oops function returns an error, thus when it is called in the main methos, the err variable cannot be nil, thus the error is returned.

An error occurred: you caused this.
guess right

Errors are only returned when the right thing does not happen, the guessKD function requires a “KD” argument are an error will be returned.

kd, err := guessKD(“kd-kd”)
...
> output: An error occurred: you caused this.
kd, err := guessKD(“KD”)
> output: kd ? : You are good

We’ve seen many ways to create errors using the standard library and how to build functions that return errors in an idiomatic way. using the standard library errors

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade