Handle a specific error in golang

I am trying to just ignore the error csv.ErrFieldCountin our code, but cannot just look at this 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 panised error line 11535, column 0: wrong number of fields in line

+4
source share
3 answers

csv.Readerdoes not return this error, it returns csv.ParseError. First you need to check if you have a ParseError, and then check the Err field:

if err, ok := err.(*csv.ParseError); ok && err.Err == csv.ErrFieldCount {
    return nil
}
+11
source

, ( , ). Read() error, * csv.ParseError, :

record, err := reader.Read()
if err != nil {
    if perr, ok := err.(*csv.ParseError); ok && perr.Err == csv.ErrFieldCount {
        return nil
    }
    return err
}
+3

Set FieldsPerRecord in the CSV Reader structure as a negative number. Then ParseErrors for unequal field counting will not occur.

Look here:

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

+2
source

Source: https://habr.com/ru/post/1618030/


All Articles