Home > Blockchain >  Go - errors.As failing to unwrap custom error type
Go - errors.As failing to unwrap custom error type

Time:12-16

I'm trying to use the Go stdlib package errors to unwrap a custom error type using errors.As, however it seems as though the check is failing and I cannot extract the underlying error.

I've extracted a minimal reproducible example:

package main

import (
    "errors"
    "fmt"
)

type myError struct {
    err error
}

func (m myError) Error() string {
    return fmt.Sprintf("my error: %s", m.err)
}

func retError() error {
    return &myError{errors.New("wrapped")}
}

func main() {
    var m myError
    if err := retError(); errors.As(err, &m) {
        fmt.Println("unwrapped", m.err)
    } else {
        fmt.Println(err)
    }
}

https://go.dev/play/p/I7BNk4-rDIB - the example on the Go playground. If launched, it will print "my error: wrapped" instead of the expected "unwrapped wrapped".

The example from the errors.As documentation works, and I can't seem to understand what am I doing incorrectly - I'm passing a *myError to errors.As, which seems to be correct (since passing a myError raises a panic: target must be a non-nil pointer, which is expected).

CodePudding user response:

Instead of:

func retError() error {
    return &myError{errors.New("wrapped")}
}

Do:

func retError() error {
    return myError{errors.New("wrapped")}
}
  • Related