aboutsummaryrefslogtreecommitdiff
path: root/echo/error_handler.go
diff options
context:
space:
mode:
Diffstat (limited to 'echo/error_handler.go')
-rw-r--r--echo/error_handler.go77
1 files changed, 77 insertions, 0 deletions
diff --git a/echo/error_handler.go b/echo/error_handler.go
new file mode 100644
index 0000000..c32fe86
--- /dev/null
+++ b/echo/error_handler.go
@@ -0,0 +1,77 @@
1package echo
2
3import (
4 "bytes"
5 "fmt"
6 "html/template"
7 "net/http"
8 "path"
9
10 "github.com/labstack/echo/v4"
11)
12
13// Copied from echo and tweaked to make our errors nicer
14func ErrorHandler(templatePath string, funcs template.FuncMap) func(error, echo.Context) {
15 return func(err error, c echo.Context) {
16 defer func() {
17 if r := recover(); r != nil {
18 if c.Echo().Debug {
19 c.String(http.StatusInternalServerError, fmt.Sprintf("Error while processing error page. %s", r))
20 } else {
21 c.String(http.StatusInternalServerError, "Error while processing error page.")
22 }
23 }
24 }()
25
26 he, ok := err.(*echo.HTTPError)
27 if ok {
28 if he.Internal != nil {
29 if herr, ok := he.Internal.(*echo.HTTPError); ok {
30 he = herr
31 }
32 }
33 } else {
34 he = &echo.HTTPError{
35 Code: http.StatusInternalServerError,
36 Message: http.StatusText(http.StatusInternalServerError),
37 }
38 }
39
40 t, err := template.New("").Funcs(funcs).ParseFiles(
41 path.Join(templatePath, "404.tpl"),
42 path.Join(templatePath, "40x.tpl"),
43 path.Join(templatePath, "50x.tpl"),
44 path.Join(templatePath, "header.tpl"),
45 path.Join(templatePath, "footer.tpl"),
46 )
47 if err != nil {
48 he = &echo.HTTPError{
49 Code: http.StatusInternalServerError,
50 Message: http.StatusText(http.StatusInternalServerError),
51 }
52 }
53
54 path := "50x.tpl"
55 if he.Code == 404 {
56 path = "404.tpl"
57 } else if he.Code >= 400 && he.Code <= 499 {
58 path = "40x.tpl"
59 }
60
61 // Send response
62 if !c.Response().Committed {
63 if c.Request().Method == http.MethodHead { // Issue #608
64 err = c.NoContent(he.Code)
65 } else {
66 buf := bytes.Buffer{}
67 if err = t.ExecuteTemplate(&buf, path, nil); err != nil {
68 err = c.String(he.Code, fmt.Sprintf("%s", he.Message))
69 }
70 c.HTMLBlob(he.Code, buf.Bytes())
71 }
72 if err != nil {
73 c.Echo().Logger.Error(err)
74 }
75 }
76 }
77}