aboutsummaryrefslogtreecommitdiff
path: root/echo/error_handler.go
blob: bfbcfb62ebc9a8de1f537c7d18031c57c05893bc (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package echo

import (
	"bytes"
	"fmt"
	"html/template"
	"io/fs"
	"net/http"

	"github.com/labstack/echo/v4"
)

// Copied from echo and tweaked to make our errors nicer
func ErrorHandler(templates fs.FS, funcs template.FuncMap) func(error, echo.Context) {
	return func(err error, c echo.Context) {
		defer func() {
			if r := recover(); r != nil {
				if c.Echo().Debug {
					c.String(http.StatusInternalServerError, fmt.Sprintf("Error while processing error page. %s", r))
				} else {
					c.String(http.StatusInternalServerError, "Error while processing error page.")
				}
			}
		}()

		he, ok := err.(*echo.HTTPError)
		if ok {
			if he.Internal != nil {
				if herr, ok := he.Internal.(*echo.HTTPError); ok {
					he = herr
				}
			}
		} else {
			he = &echo.HTTPError{
				Code:    http.StatusInternalServerError,
				Message: http.StatusText(http.StatusInternalServerError),
			}
		}

		t, err := template.New("").Funcs(funcs).ParseFS(
			templates,
			"404.tpl",
			"40x.tpl",
			"50x.tpl",
			"header.tpl",
			"footer.tpl",
		)
		if err != nil {
			he = &echo.HTTPError{
				Code:    http.StatusInternalServerError,
				Message: http.StatusText(http.StatusInternalServerError),
			}
		}

		path := "50x.tpl"
		if he.Code == 404 {
			path = "404.tpl"
		} else if he.Code >= 400 && he.Code <= 499 {
			path = "40x.tpl"
		}

		// Send response
		if !c.Response().Committed {
			if c.Request().Method == http.MethodHead { // Issue #608
				err = c.NoContent(he.Code)
			} else {
				buf := bytes.Buffer{}
				if err = t.ExecuteTemplate(&buf, path, nil); err != nil {
					err = c.String(he.Code, fmt.Sprintf("%s", he.Message))
				}
				c.HTMLBlob(he.Code, buf.Bytes())
			}
			if err != nil {
				c.Echo().Logger.Error(err)
			}
		}
	}
}