恐慌:错误:*目标必须是接口或在 Go 中实现错误

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

我正在 Go 中制作 json 解组错误处理函数:

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
    }
}

但是errors.As()出现了恐慌:panic: errors: *target must be interface or implement error.

我们可以从github.com/pkg/errors documentation:

中了解到什么是target

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

问题是 json.UnmarshalTypeErrorjson.SyntaxError 实际上都实现了 error 接口。我们可以从encoding/json documentation中了解到。所以我不知道我做错了什么。即使将 uterrserr 显式转换为 interface{} 也无法挽救这种情况。

github.com/pkg/errors 和标准 errors 包中都会发生恐慌。

errors.As 的文档指出:

As will panic if target is not a non-nil pointer to either a type that implements error, or to any interface type. As returns false if err is nil.

所以你必须考虑以下几点:

  1. json.UnmarshalTypeError 没有实现 error.
  2. *json.UnmarshalTypeError 可以,因为方法 Error() string 有一个指针接收器 (docs)
  3. 根据文档,errors.As 需要一个指向实现 error 的指针,因此您需要 **json.UnmarshalTypeError

将代码更改为:

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