Handle a specific error in golang

huangapple go评论96阅读模式
英文:

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:

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

答案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.

huangapple
  • 本文由 发表于 2015年12月1日 05:45:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/34008600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定