Handle a specific error in golang

2019-04-28 15:51发布

I am trying to simply ignore the csv.ErrFieldCount error in our code but cannot seem to only look at that one error. What am I doing wrong here?

record, err := reader.Read()
if err != nil {
    if err == csv.ErrFieldCount {
        return nil
    }
    return err
}

But when I run the code the last line of the csv file gives me this error paniced line 11535, column 0: wrong number of fields in line

3条回答
对你真心纯属浪费
2楼-- · 2019-04-28 16:04

csv.Reader doesn't return that error, it returns a csv.ParseError. You first need to check if you have a ParseError, then check the Err field:

if err, ok := err.(*csv.ParseError); ok && err.Err == csv.ErrFieldCount {
    return nil
}
查看更多
小情绪 Triste *
3楼-- · 2019-04-28 16:12

Yeah its not really well documented (that is, glancing at the documentation doesn't give you the answer very quickly). Although Read() returns an error, its actually an instance of a *csv.ParseError which you can assert and check:

record, err := reader.Read()
if err != nil {
    if perr, ok := err.(*csv.ParseError); ok && perr.Err == csv.ErrFieldCount {
        return nil
    }
    return err
}
查看更多
成全新的幸福
4楼-- · 2019-04-28 16:15

Set FieldsPerRecord in the CSV Reader struct to be a negative number. Then ParseErrors for unequal field counts will not occur.

See here:

https://golang.org/pkg/encoding/csv/#example_Reader_options

查看更多
登录 后发表回答