如何处理低级别的net/http错误?

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

How to handle low-level net/http errors?

问题

使用我的golang net/http服务器时,偶尔会出现类似以下错误的情况:

2017/08/04 15:06:25 http: Accept error: accept tcp 127.0.0.1:80: accept4: too many open files; retrying in 1s

这些错误会在stderr中显示。可能是由于某个地方缺少了Close()导致的bug,但这不是我的问题所在。

我想知道的是,在go语言中是否有一种简单的方法来以编程方式捕获这些或类似的错误?<strike>我之所以知道这个错误是因为它被记录下来了。ListenAndServe()函数不会返回错误。是否有其他方法可以通知我这些错误?</strike>具体来说:我如何访问底层监听器的错误?ListenAndServe()函数不会返回底层监听器的错误(至少不是全部)。

(已编辑)

英文:

With my golang net/http server, I occasionally get errors like

2017/08/04 15:06:25 http: Accept error: accept tcp 127.0.0.1:80: accept4: too many open files; retrying in 1s

on stderr. There might be a bug with a missing Close() somewhere, but this is not what my question is about.

What I would like to know is whether there is an easy way to catch these or similar errors programmatically in go? <strike>I only know about this error because it's logged. ListenAndServe() does not return an error. Is there some other way to get notified of errors like these?</strike> Specifically: how do I access the errors of the underlying listener? ListenAndServe() does not return errors from the underlying listener (at least not all of them).

(edited)

答案1

得分: 2

net/http将所有错误记录到server.ErrorLog。您可以使用它来拦截日志消息,但是从这些日志中以编程方式提取多少数据并不明显。

英文:

net/http logs all errors to server.ErrorLog. You can use that to intercept the log messages, but it is not obvious how much data you can pull from those logs programatically.

答案2

得分: 1

如果你查看(*http.Server).Serve()的实现这里,你会发现你可以定义自己的类来实现net.Listener,然后将其传递给Serve()函数,而不是使用ListenAndServe(),后者会在那里放置一个默认的监听器。在你的代码中,可以让它在出现错误时panic,然后稍后通过recover从该panic中恢复,或者实现任何其他错误处理逻辑。

英文:

If you look at how (*http.Server).Serve() is implemented here, it is clear that you can just define your own class that implements net.Listener and give it to the Serve() function, instead of using ListenAndServe(), which puts a default listener there. Make it panic on error and later recover from that panic in your code, or implement any other error handling logic.

huangapple
  • 本文由 发表于 2017年8月4日 23:18:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/45510348.html
匿名

发表评论

匿名网友

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

确定