Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go – errors.As failing to unwrap custom error type

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

>Solution :

Instead of:

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

Do:

func retError() error {
    return myError{errors.New("wrapped")}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading