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")
}
}
An error chain links multiple errors together so you can see the full history of what went wrong, from the root cause to the final failure. It works like a breadcrumb trail that helps you trace exactly where a problem started in your code. You use this when a high-level function fails because a lower-level function failed, and you need to keep both messages.