From 52ea329b8b0603f9c306bd559f38bab11979fd98 Mon Sep 17 00:00:00 2001 From: Christian Claus Date: Mon, 23 Apr 2018 21:27:36 +0200 Subject: [PATCH] Add recovery to http handler --- cmd/swd/main.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/cmd/swd/main.go b/cmd/swd/main.go index 85318b5..90efec0 100644 --- a/cmd/swd/main.go +++ b/cmd/swd/main.go @@ -6,6 +6,7 @@ import ( log "github.com/sirupsen/logrus" "golang.org/x/net/webdav" "net/http" + "errors" ) func main() { @@ -31,7 +32,7 @@ func main() { Handler: wdHandler, } - http.Handle("/", app.NewBasicAuthWebdavHandler(a)) + http.Handle("/", wrapRecovery(app.NewBasicAuthWebdavHandler(a))) connAddr := fmt.Sprintf("%s:%s", config.Address, config.Port) @@ -51,3 +52,25 @@ func main() { log.Fatal(http.ListenAndServe(connAddr, nil)) } } + +func wrapRecovery(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var err error + defer func() { + r := recover() + switch t := r.(type) { + case string: + err = errors.New(t) + case error: + err = t + default: + err = errors.New("Unknown error") + } + + log.WithError(err).Error("An error occurred handling a webdav request") + http.Error(w, "Internal server error", http.StatusInternalServerError) + }() + + handler.ServeHTTP(w, r) + }) +}