简体   繁体   中英

Best way to handle error from Write call in Go http handler

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.

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

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

  • errors caused by bugs in your server ( eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM