-1

I am probably missing something really simple here:

package main

import (
    "fmt"
    "strconv"
    "reflect"
)

func main() {
    s := "abd"
    fmt.Println(s)
    _, err := strconv.Atoi(s)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(reflect.TypeOf(err))

    fmt.Println(err.Err)

}

I am trying to extract the error itself e.g. ErrSyntax or ErrRange, but I am not able to do so.

After looking at:

https://golang.org/src/strconv/atoi.go?s=3604:3671#L16

I see that err is a pointer to strconv.NumError

    15  // A NumError records a failed conversion.
    16  type NumError struct {
    17      Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat)
    18      Num  string // the input
    19      Err  error  // the reason the conversion failed (ErrRange, ErrSyntax)
    20  }

And Err is the field that holds either ErrRange of ErrSyntax. Therefore, I thought that err.Err would work, but I get:

err.Err undefined (type error has no field or method Err

Err is public, am I missing something with visibility rules?

What am I missing?

Akavall
  • 82,592
  • 51
  • 207
  • 251

1 Answers1

3

Use a type assertion to get the *strconv.NumError value:

if e, ok := err.(*strconv.NumError); ok {
    fmt.Println("e.Err", e.Err)
}

playground example

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242