Home  >  Article  >  Backend Development  >  How to use error.Is to check if the error is strconv.NumError

How to use error.Is to check if the error is strconv.NumError

WBOY
WBOYforward
2024-02-06 09:42:131015browse

如何使用 error.Is 检查错误是否为 strconv.NumError

Question content

I have this error

The error type is ParseInt. How to check this error I'm assuming I would use errors.Is but not sure what I would do in this case


Correct Answer


https ://pkg.go.dev/[email protected]#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.)
}

The error type is parseint.

"parseint" is the name of the "failure function", a function that returns an error. The actual error type is *strconv.numerror. You can check it and the function name like this:

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

The above is the detailed content of How to use error.Is to check if the error is strconv.NumError. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete