Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle a specific error in golang

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

like image 753
Jared Mackey Avatar asked Nov 30 '15 21:11

Jared Mackey


People also ask

How do you catch exceptions in Golang?

This method is also known as try-catch-finally In this method, in the try block the error-free code has been executed and if it has found some issue it will be handled in the catch block and finally block will be executed all the things at any cost.

What is err != Nil in Golang?

if err != nil { return err } > is outweighed by the value of deliberately handling each failure condition at the point at which they occur. Key to this is the cultural value of handling each and every error explicitly.

Does Go handling error?

Error handling in Go is a little different than other mainstream programming languages like Java, JavaScript, or Python. Go's built-in errors don't contain stack traces, nor do they support conventional try / catch methods to handle them.

How do I print an error message in Go?

@shan error is an interface that implements Error() string . Call this method it to retrieve the message. Alternatively, the fmt package can process error values and prints the message automatically, so you can simply use fmt. Println(err) to print the message.


3 Answers

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
}
like image 151
JimB Avatar answered Oct 19 '22 08:10

JimB


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

like image 10
Kerby Shedden Avatar answered Oct 19 '22 08:10

Kerby Shedden


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
}
like image 7
Simon Whitehead Avatar answered Oct 19 '22 10:10

Simon Whitehead