如何在Go语言中检查特定的网络错误?

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

How do I check a specific network error in Go?

问题

我正在编写一个服务器,并且希望处理来自conn.Read()的错误。具体来说,如果客户端关闭了连接,我希望什么都不做,但如果是其他错误,我希望记录错误日志。我遇到了以下问题:

  1. 文档似乎没有说明conn.Read()可能返回的错误。
  2. 客户端关闭连接似乎是一个EOF错误。结果发现它的类型是error.errorString。真的吗?

所以基本上我必须将错误与"EOF"进行字符串比较,以确定错误是预期的还是真正的错误?!我是否漏掉了什么?因为这似乎是一个巨大的疏忽...

英文:

I have a server that I am writing, and I want to handle errors from conn.Read(). Specifically, I want to do nothing in the case that the client has closed the connection, but log the error if it is any other error. I have encountered the following problems:

  1. The documentation does not seem to say what the errors that conn.Read() can return.
  2. Connection-closed-by-client seems to be an EOF error. Turns out that it's type is error.errorString. Seriously?

So basically I have to do a string comparison to "EOF" to tell if my error is expected or a genuine error?!? Am I missing something? Because this seems like a huge oversight at the moment...

答案1

得分: 2

好的,以下是翻译好的内容:

不,它是string类型,因为它在这里被定义为:

import "errors"
...
var EOF = errors.New("EOF")

errors.New(string)返回的实际上是一个可转换为string类型的类型,因为这个类型errorString仅仅嵌入了你传递给error.New(string)的字符串,其唯一目的是在其上定义Error() string方法,以满足error接口的要求。

但是你可以这样测试特定的错误(文件末尾):

import "io"
...
if err == io.EOF {
...

也就是说,你不是在比较字符串,而是在比较某个特定库模块(在本例中是"io")导出的一个众所周知的变量的地址。

英文:

Well, no, it's string because it's defined as

import "errors"
...
var EOF = errors.New("EOF")

and what errors.New(string) returns is really a type convertible to string because that type, errorString merely embeds a string you're passing to error.New(string) with the sole purpose of defining the Error() string method on it—to satisfy the error interface.

But you test for this specific error (end of file) like this:

import "io"
...
if err == io.EOF {
...

That is, you're not comparing strings but rather addresses of a well-known variable exported by a certain library module ("io" in this case).

huangapple
  • 本文由 发表于 2014年7月22日 17:42:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/24883937.html
匿名

发表评论

匿名网友

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

确定