How to Unwrap Errors in Go with errors.Unwrap

Use errors.Unwrap to access the underlying error in a chain, or errors.Is and errors.As to check for specific error types.

Use errors.Unwrap(err) to retrieve the underlying error from a wrapped error, or errors.Is and errors.As to check for specific error types in a chain.

import "errors"

func handle(err error) {
    // Unwrap to get the next error in the chain
    if unwrapped := errors.Unwrap(err); unwrapped != nil {
        fmt.Println("Wrapped error:", unwrapped)
    }

    // Check if the chain contains a specific error
    if errors.Is(err, ErrInsecurePath) {
        fmt.Println("Found insecure path error")
    }

    // Extract a specific type from the chain
    var targetErr *ArgumentError
    if errors.As(err, &targetErr) {
        fmt.Println("Argument index:", targetErr.Index)
    }
}