Search code examples
gostrconv

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


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).


Solution

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