From c670f39db8004f0d8a27d180463784ddc6baf5af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Matczuk?= Date: Tue, 8 Nov 2022 16:22:11 +0100 Subject: [PATCH] proxy: improve error handling if there is no response This patch allows to distinguish between status codes * 502 - network error, failed to dial * 504 - network error, dial timeout * 500 - other error Relates to #51 --- proxy.go | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/proxy.go b/proxy.go index 2ed3535b..8cbf433a 100644 --- a/proxy.go +++ b/proxy.go @@ -168,16 +168,29 @@ func (proxy *ProxyHttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) resp = proxy.filterResponse(resp, ctx) if resp == nil { - var errorString string - if ctx.Error != nil { - errorString = "error read response " + r.URL.Host + " : " + ctx.Error.Error() - ctx.Logf(errorString) - http.Error(w, ctx.Error.Error(), 502) + var ( + errorString string + code int + ) + + if e, ok := ctx.Error.(net.Error); ok { + if e.Timeout() { + errorString = "timed out connecting to remote host: " + e.Error() + code = http.StatusGatewayTimeout + } else { + errorString = "failed to connect to remote host: " + e.Error() + code = http.StatusBadGateway + } + } else if ctx.Error != nil { + errorString = "failed to read response from remote host: " + e.Error() + code = http.StatusInternalServerError } else { - errorString = "error read response " + r.URL.Host - ctx.Logf(errorString) - http.Error(w, errorString, 502) + errorString = "failed to read response from remote host: " + r.URL.Host + code = http.StatusInternalServerError } + + ctx.Logf(errorString) + http.Error(w, errorString, code) return } ctx.Logf("Copying response to client %v [%d]", resp.Status, resp.StatusCode)