英文:
Handle a specific error in golang
问题
我正在尝试在我们的代码中忽略csv.ErrFieldCount
错误,但似乎无法只关注这个错误。我在这里做错了什么?
record, err := reader.Read()
if err != nil {
if err == csv.ErrFieldCount {
return nil
}
return err
}
但是当我运行代码时,csv文件的最后一行给出了这个错误:line 11535, column 0: wrong number of fields in line
。
英文:
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
答案1
得分: 19
csv.Reader
不会返回该错误,它会返回一个csv.ParseError
。你首先需要检查是否有ParseError
,然后再检查Err
字段:
if err, ok := err.(*csv.ParseError); ok && err.Err == csv.ErrFieldCount {
return nil
}
英文:
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
}
答案2
得分: 10
将CSV Reader结构中的FieldsPerRecord设置为负数。这样,就不会发生由于字段计数不等而导致的解析错误。
请参考这里的链接:
https://golang.org/pkg/encoding/csv/#example_Reader_options
英文:
Set FieldsPerRecord in the CSV Reader struct to be a negative number. Then ParseErrors for unequal field counts will not occur.
See here:
答案3
得分: 9
是的,它的文档并不是非常完善(也就是说,浏览文档并不能很快地给出答案)。虽然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
}
英文:
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
得分: 1
从Go 1.13开始,我认为处理这个问题的惯用方式是使用errors.Is
:
if errors.Is(err, csv.ErrFieldCount) {
return nil
}
更多详细信息,请参阅在Go 1.13中处理错误。
英文:
As of Go 1.13 I think the idiomatic way to handle this would be to use errors.Is
:
if errors.Is(err, csv.ErrFieldCount) {
return nil
}
See Working with Errors in Go 1.13 for more details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论