CodeBlanks Logo Icon CodeBlanks

errors.Is and errors.As

Learn error wrapping and errors.Is, errors.As usage.

errors.Is and errors.As

Wrapped errors can't be compared with == because the outer error is a different value. To look inside the chain:

err := fmt.Errorf("profil: %w", ErrBulunamadi)
fmt.Println(err == ErrBulunamadi)          // false
fmt.Println(errors.Is(err, ErrBulunamadi)) // true

var dh *DogrulamaHatasi
if errors.As(err, &dh) {
    fmt.Println("alan:", dh.Alan)
}

errors.Is searches for a specific error value, errors.As for a specific error type.

Comparing correctly

Rule: in error checks always use errors.Is instead of ==; then your code keeps working even if the error is wrapped later. The standard library does the same: errors.Is(err, fs.ErrNotExist), errors.Is(err, context.DeadlineExceeded), errors.Is(err, sql.ErrNoRows).

Practice Search the chain

Create ErrYok := errors.New("yok") and err := fmt.Errorf("katman 2: %w", fmt.Errorf("katman 1: %w", ErrYok)). Print err == ErrYok and errors.Is(err, ErrYok) on one line.

Starter code

main.go
package main

import (
    "errors"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "errors"
    "fmt"
)

func main() {
    ErrYok := errors.New("yok")
    err := fmt.Errorf("katman 2: %w", fmt.Errorf("katman 1: %w", ErrYok))
    fmt.Println(err == ErrYok, errors.Is(err, ErrYok))
}

Expected output

false true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is a pointer (<code>&amp;dh</code>) passed to <code>errors.As</code>?

  • So it can write the found error into that variable Correct answer
  • Because it's faster
  • It isn't required
  • For a nil check

Explanation: If As finds the requested type in the chain, it assigns the value to the target variable; that needs the target's address.

2 Search for the type

Question
var dh *DogrulamaHatasi
if errors.____(err, &dh) {
    fmt.Println(dh.Alan)
}
Answer
var dh *DogrulamaHatasi
if errors.As(err, &dh) {
    fmt.Println(dh.Alan)
}

Explanation: errors.As finds the requested type in the chain and assigns it to the target.

3 Question and tool

Term Meaning
Is this error ErrX? errors.Is
Is this error of type *MyErr? errors.As
Unwrap one level errors.Unwrap
err == ErrX Breaks once wrapped

All lessons in Beginner