dongzhenbi8919 2019-03-13 22:24
浏览 281

在Go http处理程序中处理Write调用错误的最佳方法

What is best way to handle Write error in http handler.

func hello(w http.ResponseWriter, r *http.Request) {
  n, err := w.Write([]byte("hi"))
  // how should we handle this error?
}

I suppose I can take n and try to Write again with remainder of bytes.

  • 写回答

1条回答 默认 最新

  • douyinyi7766 2019-06-27 17:48
    关注

    At this point you will only see two types of errors:

    • network errors, (e.g. if the client goes away while you are trying to send data), or

    • errors caused by bugs in your server (e.g. if you manually set Content-Length and then try to write more data than you claimed, you will get ErrContentLength).

    You can look at the implementation of the response class in net/http/server.go, to get an idea of errors you may see from the default ResponseWriter. How to handle these errors?

    • For errors like ErrContentLength, which indicate bugs in the server, it seems reasonable to log these, because the error messages may help to fix the server.

    • To me it would seem reasonable to simply ignore network errors, but of course these could also be logged, if needed.

    • One of the first things Write() does, is to make sure the headers are sent. Thus, by the time you see an error code returned by Write(), it will be too late to attempt to change the HTTP status code. Given this, it seems not worth trying (and probably is impossible) to notify the client that something went wrong.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog