首页 > 文章列表 > 检测错误是否为strconv.NumError,使用error.Is的方法

检测错误是否为strconv.NumError,使用error.Is的方法

175 2024-04-26
问题内容

我有这个错误

错误的类型为 ParseInt。如何检查此错误 我假设我会使用 errors.Is 但不确定在这种情况下我会如何做


正确答案


https://pkg.go.dev/[电子邮件受保护]#numerror

type numerror struct {
    func string // the failing function (parsebool, parseint, parseuint, parsefloat, parsecomplex)
    num  string // the input
    err  error  // the reason the conversion failed (e.g. errrange, errsyntax, etc.)
}

错误的类型为 parseint。

"parseint"“失败函数” 的名称,即返回错误的函数。实际的错误类型是 *strconv.numerror。您可以像这样检查它和函数名称:

if e, ok := err.(*strconv.NumError); ok && e.Func == "ParseInt" {
    // do xyz
}