-
Notifications
You must be signed in to change notification settings - Fork 2
/
recover.go
46 lines (38 loc) · 1.25 KB
/
recover.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package page
import (
"fmt"
"net/http"
"runtime/debug"
"strings"
"github.com/ministryofjustice/opg-go-common/template"
"github.com/ministryofjustice/opg-modernising-lpa/internal/localize"
)
type recoverError struct {
err any
stack []byte
}
func (e recoverError) Error() string { return "recover error" }
func (e recoverError) Title() string { return fmt.Sprint(e.err) }
func (e recoverError) Data() any { return string(e.stack) }
func Recover(tmpl template.Template, logger Logger, bundle Bundle, next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
logger.Request(r, recoverError{err: err, stack: debug.Stack()})
w.WriteHeader(http.StatusInternalServerError)
appData := AppData{CookieConsentSet: true, Paths: Paths}
if strings.HasPrefix(r.URL.Path, "/cy/") {
appData.Lang = localize.Cy
} else {
appData.Lang = localize.En
}
appData.Localizer = bundle.For(appData.Lang)
if terr := tmpl(w, &errorData{App: appData}); terr != nil {
logger.Print(fmt.Sprintf("Error rendering page: %s", terr.Error()))
http.Error(w, "Encountered an error", http.StatusInternalServerError)
}
}
}()
next.ServeHTTP(w, r)
}
}