go - panic : errors: *target must be interface or

我正在 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:panic: errors: *target must be interface or implement error

我们可以从github.com/pkg/errors documentation中了解到什么是目标:

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

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

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

最佳答案

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
}

关于go - panic : errors: *target must be interface or implement error in Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69447919/

相关文章:

django - 使用 drf-spectacular 为 django API 定义组件模式

c# - Powershell 到 C# 语法转换

ios - 'CC_MD5' is deprecated : first deprecated in

next.js - Next JS 中的 Font Awesome 6(测试版)和动态图标名称

r - 如何按日期对数据框进行排序。但日期列在宿舍

python - youtube_dl - 无法阻止发布错误日志

c - 释放函数内部的指针,并在 main 中使用它

c++ - C++ 中具有不同数据成员的模板结构

c - 为什么这种 strcpy 的使用被认为是错误的?

c - C如何计算混合的int和float数据类型