Home > other >  panic: errors: *target must be interface or implement error in Go
panic: errors: *target must be interface or implement error in Go

Time:10-06

I am making a json unmarshalling error handling function in Go:

import "github.com/pkg/errors"

func parseJSONError(err error) {
    var uterr json.UnmarshalTypeError

    if errors.As(err, &uterr) {
        //...
        return
    }

    var serr json.SyntaxError

    if errors.As(err, &serr) {
        //...
        return
    }
}

But there is a panic in errors.As(): panic: errors: *target must be interface or implement error.

What is target we can learn from the github.com/pkg/errors documentation:

func As(err error, target interface{}) bool

The problem is that both json.UnmarshalTypeError and json.SyntaxError actually implement the error interface. We can learn it from the encoding/json documentation. So I do not have any idea what I am doing wrong. Even explicit casting uterr and serr to the interface{} does not save the situation.

The panic occurs in both github.com/pkg/errors and standard errors packages.

CodePudding user response:

  1. json.UnmarshalTypeError does not implement error.
  2. *json.UnmarshalTypeError does (because Error() string has pointer receiver)
  3. errors.As wants a pointer to what implement error, so you need **json.UnmarshalTypeError

Change to:

uterr := &json.UnmarshalTypeError{}
if errors.As(err, &uterr) {
    // ...
    return
}

  • Related