ProgramGuru

errors.As()

Start with errors.As()

errors.As searches an error chain for a value assignable to a requested error type.

What you’ll learn

  • Explain the main purpose of errors.as().
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Suppose a custom error struct contains an HTTP-like status code. When it is wrapped with extra context, direct type assertion against the outer error fails. errors.As(err, &target) can locate the typed error inside the chain.

The target must be a non-nil pointer to a compatible variable. With var issue *StatusError, pass &issue. Use errors.Is for sentinel identity and errors.As for type-based handling.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for errors aserrors.As obtains typed error details through wrappers.*StatusError{503}Step 1Wrap causeStep 2errors.As(&status)Step 3Read status.CodeStep 4errors.As obtains typed error details through wrappers.
errors.As obtains typed error details through wrappers.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"errors"
	"fmt"
)

type StatusError struct{ Code int }

func (e *StatusError) Error() string { return fmt.Sprintf("status %d", e.Code) }
func request() error                 { return fmt.Errorf("request failed: %w", &StatusError{Code: 503}) }
func main() {
	err := request()
	var status *StatusError
	if errors.As(err, &status) {
		fmt.Println("Status:", status.Code)
	}
}

Output

Status: 503

Trace what the program does

request returns a wrapped *StatusError. errors.As finds the underlying error and assigns it to status, so the program prints 503.

Avoid common mistakes

  • Passing the wrong target shape can cause a panic or fail the desired type match.
  • The target variable is populated only when errors.As returns true.

Try it yourself

Change the code to use 404 and add another layer of fmt.Errorf wrapping. Confirm errors.As still retrieves the code.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

When should you use errors.As?
Choose one answer. You can try again.

Answer and explanation

To extract an error of a particular type from a chain

Correct. request returns a wrapped *StatusError.

What you should remember

You have practiced errors.As() in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Panic in Go →