英文:
How do I check a specific network error in Go?
问题
我正在编写一个服务器,并且希望处理来自conn.Read()的错误。具体来说,如果客户端关闭了连接,我希望什么都不做,但如果是其他错误,我希望记录错误日志。我遇到了以下问题:
- 文档似乎没有说明conn.Read()可能返回的错误。
- 客户端关闭连接似乎是一个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:
- The documentation does not seem to say what the errors that conn.Read() can return.
- 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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论