How to Create an Error Chain in Go

Create an error chain in Go by wrapping errors with fmt.Errorf and the %w verb to preserve the original error context.

Create an error chain in Go by wrapping the original error with fmt.Errorf using the %w verb, which preserves the error context for later unwrapping.

package main

import (
	"errors"
	"fmt"
)

func main() {
	rootErr := fmt.Errorf("connection failed")
	wrappedErr := fmt.Errorf("%w: timeout occurred", rootErr)

	if errors.Is(wrappedErr, rootErr) {
		fmt.Println("Error chain detected")
	}
}