How to check err type returned from function(strconv.Atoi)

1.1k views Asked by At

I have the following basic code that tests strconv.Atoi():

package main

import (
        "fmt"
        "strconv"
)

func main() {

        var a int
        var b string
        var err Error

        b = "32"

        a,err = strconv.Atoi(b)

        fmt.Println(a)
        fmt.Println(err)

}

I want to handle if there was an Error in strconv.Atoi(), and specifically if the error was due to syntax or range, conditions that strconv.Atoi() can provide. To do that I have tried this:

package main

import (
        "os"
        "fmt"
        "strconv"
)

func main() {

        var a int
        var b string
        var err error

        b = "32"

        a,err = strconv.Atoi(b)

        if(err.Err == ErrSyntax) {
                fmt.Println("ERROR")
                os.Exit(1)
        }

        fmt.Println(a)
        fmt.Println(err)

}

And I get this as result:

% go build test.go
# command-line-arguments
./test.go:19:8: err.Err undefined (type error has no field or method Err)
./test.go:19:16: undefined: ErrSyntax

I would like to understand how to process the two errors Atoi can return (ErrSyntax, ErrRange).

2

There are 2 answers

2
kozmo On BEST ANSWER

You can use errors package (Working with Errors in Go 1.13):

if errors.Is(err, strconv.ErrSyntax) {
    fmt.Println("syntax error")
    os.Exit(1)
}
0
Seebs On

Package docs for a package show the names without the package qualifier, to use them from elsewhere, you have to qualify them. So try strconv.ErrSyntax.

But that won't quite help, because there's no .Err member of a generic error interface. To check that, you'd have to know that the returned error is in fact a strconv.*NumError. Which it should be, according to the docs.

https://play.golang.org/p/UKL6kKDqSx4

    if err != nil && err.(*strconv.NumError).Err == strconv.ErrSyntax {
        fmt.Println("syntax error")
        os.Exit(1)
    }