Go Error Handling Explained for Beginners

Updated 4 min read
Go Error Handling featured image: cards showing err != nil, %w wrapping and errors.Is

Go error handling is simple: functions return an error value, and you check it right away. In this post, you will learn the if err != nil pattern, how to add context to errors and how to check them safely. Each idea comes with a short example that you can run yourself.

You have already seen errors returned as a second value in writing and calling functions in Go. Also, error is just an interface, which you met in interfaces in Go with examples. Now we will put both ideas together.

What Is Go Error Handling?

Many languages throw exceptions that jump far away from where the problem happened. Go does not. Instead, an error is a normal value that a function returns, so you deal with it on the very next line.

Think of a delivery app. If the restaurant is closed, the app tells you immediately rather than failing silently later. In the same way, Go error handling makes every failure visible right where it happens.

The if err != nil Pattern

n, err := strconv.Atoi("abc")
if err != nil {
	fmt.Println("Error:", err)
	return
}
fmt.Println(n)
// Error: strconv.Atoi: parsing "abc": invalid syntax

The function returns a value and an error. When the error is nil, everything worked. Otherwise, you handle it first and usually return early, so the happy path stays at the left edge of your code.

Returning Errors from Your Functions

var ErrNotFound = errors.New("user not found")

func findUser(id int) (string, error) {
	if id != 1 {
		return "", ErrNotFound
	}
	return "Asha", nil
}

In Go error handling, use errors.New to create a simple error message. By convention, the error is always the last return value. Also, error messages start with a lowercase letter and have no full stop.

Go Error Handling with Wrapped Errors

func loadUser(id int) (string, error) {
	name, err := findUser(id)
	if err != nil {
		return "", fmt.Errorf("loadUser %d: %w", id, err)
	}
	return name, nil
}

_, err := loadUser(7)
fmt.Println(err) // loadUser 7: user not found

A bare “user not found” does not say where it came from. So fmt.Errorf with the %w verb wraps the original error inside a new message. As a result, the final error reads like a trail of breadcrumbs.

Go Error Handling diagram showing an error wrapped through two layers and found again with errors.Is

Each layer adds context with %w, and errors.Is can still find the original ErrNotFound inside.

Checking Errors with errors.Is and errors.As

Sentinel Errors and errors.Is

_, err := loadUser(7)
fmt.Println(errors.Is(err, ErrNotFound)) // true

A sentinel error is a fixed error value, like ErrNotFound, that callers can test for. Because the error is wrapped, a plain == check would fail. Instead, errors.Is looks through every layer.

Custom Error Types and errors.As

type AgeError struct{ Age int }

func (e *AgeError) Error() string {
	return fmt.Sprintf("invalid age %d", e.Age)
}

err := setAge(-5) // returns &AgeError{Age: -5}

var ae *AgeError
if errors.As(err, &ae) {
	fmt.Println("Bad age:", ae.Age) // Bad age: -5
}

Any type with an Error() string method is an error. Then errors.As finds that type in the chain and gives you its fields. This is handy when callers need details, such as an HTTP status code.

Panic and Recover in Go Error Handling

func safeDivide(a, b int) (result int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return a / b, nil
}

_, err := safeDivide(10, 0)
fmt.Println(err) // recovered: runtime error: integer divide by zero

A panic stops the program for bugs that should never happen. However, recover inside a deferred function can catch it. Use this rarely, for example to keep a web server alive after one bad request.

Go Error Handling Best Practices

  • Check every error right after the call.
  • Add context with fmt.Errorf and %w as errors move up.
  • Compare with errors.Is and errors.As, never with plain text.
  • Handle an error once: either log it or return it, not both.

Common Mistakes in Go Error Handling

Error you seeWhy it happensHow to fix it
declared and not used: errThe code never checked err.Add if err != nil.
errors.Is returns falseThe code used %v, not %w.Wrap with %w.
Silent wrong dataThe error went to _ by mistake.Only ignore errors on purpose.

The %v versus %w mix-up is easy to miss, since both print the same text. Error questions also appear in my Go interview questions and answers, so test yourself there.

Official Resources

These pages come straight from the Go team, so they are always accurate and up to date.

Quick Recap

  • Go error handling treats errors as normal return values.
  • Check if err != nil right after each call and return early.
  • Wrap errors with fmt.Errorf and %w to add context.
  • Use errors.Is for fixed errors and errors.As for custom types.
  • Save panic and recover for real bugs, not normal failures.

What’s Next?

Your code is getting bigger. Next, we will organise it into packages and modules, so each part lives in its own folder.

Coming soon: Go Modules and Packages Explained Simply