@marcel91200 / caddy Mirror · read-only / commits / e3591009
Fork 0

Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS

Mirrored from https://github.com/Slazee/caddy.git

Synced Nov 14, 05:15 UTC

caddyhttp: Add handler for unhandled errors in errorChain (#3063)

* Add handler for unhandled errors in errorChain Currently, when an error chain is defined, the default error handler is bypassed entirely - even if the error chain doesn't handle every error. This results in pages returning a blank 200 OK page. For instance, it's possible for an error chain to match on the error status code and only handle a certain subtype of errors (like 403s). In this case, we'd want any other errors to still go through the default handler and return an empty page with the status code. This PR changes the "suffix handler" passed to errorChain.Compile to set the status code of the response to the error status code. Fixes #3053 * Move the errorHandlerChain middleware to variable * Style fix

Robin Lambertz committed Feb 20, 2020 at 23:00 UTC e3591009dc8cf386704f8671c54b0f97c3f75b8c
1 file changed +16 -1
modules/caddyhttp/caddyhttp.go
+16 -1
@@ -185,7 +185,8 @@ func (app *App) Provision(ctx caddy.Context) error {
185 if err != nil {
186 return fmt.Errorf("server %s: setting up server error handling routes: %v", srvName, err)
187 }
188 - srv.errorHandlerChain = srv.Errors.Routes.Compile(emptyHandler)
188 +
189 + srv.errorHandlerChain = srv.Errors.Routes.Compile(errorEmptyHandler)
190 }
191 }
192
@@ -413,6 +414,20 @@ type MiddlewareHandler interface {
414 // emptyHandler is used as a no-op handler.
415 var emptyHandler Handler = HandlerFunc(func(http.ResponseWriter, *http.Request) error { return nil })
416
417 +// An implicit suffix middleware that, if reached, sets the StatusCode to the
418 +// error stored in the ErrorCtxKey. This is to prevent situations where the
419 +// Error chain does not actually handle the error (for instance, it matches only
420 +// on some errors). See #3053
421 +var errorEmptyHandler Handler = HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
422 + httpError := r.Context().Value(ErrorCtxKey)
423 + if handlerError, ok := httpError.(HandlerError); ok {
424 + w.WriteHeader(handlerError.StatusCode)
425 + } else {
426 + w.WriteHeader(http.StatusInternalServerError)
427 + }
428 + return nil
429 +})
430 +
431 // WeakString is a type that unmarshals any JSON value
432 // as a string literal, with the following exceptions:
433 //