doujiong9915 2014-07-22 09:42
浏览 54
已采纳

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

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条回答 默认 最新

  • doutang6819 2014-07-22 10:24
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看