aboutsummaryrefslogtreecommitdiff
path: root/echo/error_handler.go
blob: a0bdd60e2a65badc7dbb8a94bc62a498f8cffd3e (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package echo

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

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

type ContentErrorHandler interface {
	Handle(echo.Context, *echo.HTTPError) error
}

type ErrorHandler interface {
	AddHandler(ContentErrorHandler, ...string)
	HandleError(error, echo.Context)
}

type HTMLErrorHandler struct {
	r        *TemplateRenderer
	fallback *template.Template
}

var _ ContentErrorHandler = (*HTMLErrorHandler)(nil)

func NewHTMLErrorHandler(r *TemplateRenderer) *HTMLErrorHandler {
	t, err := template.New("").Parse("<html><body><h1>Error</h1><pre>{{ .Message }}</pre></body></html>\n")
	if err != nil {
		panic("NewHTMLErrorHandler: error parsing fallback template")
	}
	return &HTMLErrorHandler{r: r, fallback: t}
}

func (h *HTMLErrorHandler) Handle(c echo.Context, e *echo.HTTPError) error {
	path := "50x.tpl"
	if e.Code == 404 {
		path = "404.tpl"
	} else if e.Code >= 400 && e.Code <= 499 {
		path = "40x.tpl"
	}

	buf := bytes.Buffer{}
	if !h.r.HaveTemplate(path) {
		c.Logger().Errorf("Error template %s is missing, using fallback", path)

		if err := h.fallback.Execute(&buf, e); err != nil {
			c.Logger().Errorf("Error rendering HTML error page: %s", err)
			return c.String(e.Code, e.Error())
		}
	} else {
		// Must pass nil as the data value otherwise complex templates fail
		if err := h.r.Render(&buf, path, nil, c); err != nil {
			c.Logger().Errorf("Error rendering HTML error page: %s", err)
			return c.String(e.Code, e.Error())
		}
	}

	return c.HTMLBlob(e.Code, buf.Bytes())
}

type PlainTextErrorHandler struct{}

var _ ContentErrorHandler = (*PlainTextErrorHandler)(nil)

func (h *PlainTextErrorHandler) Handle(c echo.Context, e *echo.HTTPError) error {
	return c.String(e.Code, fmt.Sprintf("%s", e.Message))
}

type JSONErrorHandler struct{}

var _ ContentErrorHandler = (*JSONErrorHandler)(nil)

func (h *JSONErrorHandler) Handle(c echo.Context, e *echo.HTTPError) error {
	code := e.Code
	message := e.Message
	if m, ok := e.Message.(string); ok {
		if c.Echo().Debug {
			message = echo.Map{"message": m, "error": e.Error()}
		} else {
			message = echo.Map{"message": m}
		}
	}

	return c.JSON(code, message)
}

type failsafeHandler struct{}

var _ ContentErrorHandler = (*failsafeHandler)(nil)

func (h *failsafeHandler) Handle(c echo.Context, e *echo.HTTPError) error {
	c.Echo().Logger.Error("Error while processing error page: %s", e)
	c.JSON(http.StatusInternalServerError, e)
	return nil
}

type EchoErrorHandler struct {
	types           []contenttype.MediaType
	typeMap         map[string]ContentErrorHandler
	failsafeHandler ContentErrorHandler
}

var _ ErrorHandler = (*EchoErrorHandler)(nil)

func NewEchoErrorHandler() *EchoErrorHandler {
	return &EchoErrorHandler{
		types:           []contenttype.MediaType{},
		typeMap:         map[string]ContentErrorHandler{},
		failsafeHandler: &failsafeHandler{},
	}
}

func NewDefaultErrorHandler(tr *TemplateRenderer) *EchoErrorHandler {
	h := NewEchoErrorHandler()

	// The order of these is important, especially when negotiating */*
	h.AddHandler(&JSONErrorHandler{}, "text/json", "application/json")
	h.AddHandler(&PlainTextErrorHandler{}, "text/plain")
	h.AddHandler(NewHTMLErrorHandler(tr), "text/html")

	return h
}

func NewNoHTMLErrorHandler() *EchoErrorHandler {
	h := NewEchoErrorHandler()

	// The order of these is important, especially when negotiating */*
	h.AddHandler(&JSONErrorHandler{}, "text/json", "application/json")
	h.AddHandler(&PlainTextErrorHandler{}, "text/plain")

	return h
}

func (h *EchoErrorHandler) AddHandler(eh ContentErrorHandler, contentTypes ...string) {
	for _, ct := range contentTypes {
		h.types = append(h.types, contenttype.NewMediaType(ct))
		h.typeMap[ct] = eh
	}
}

func (h *EchoErrorHandler) castToHttpError(e error) *echo.HTTPError {
	he, ok := e.(*echo.HTTPError)
	if ok {
		if he.Internal != nil {
			if ihe, ok := he.Internal.(*echo.HTTPError); ok {
				return ihe
			}
		}
		return he
	} else {
		return &echo.HTTPError{
			Code:    http.StatusInternalServerError,
			Message: http.StatusText(http.StatusInternalServerError),
		}
	}
}

func (h *EchoErrorHandler) negotiateContentType(r *http.Request) (ContentErrorHandler, error) {
	var err error

	ct, _, err := contenttype.GetAcceptableMediaType(r, h.types)
	if err != nil {
		err = fmt.Errorf("Error negotiating content type in error handler, falling back to JSON: %w", err)
		ct = contenttype.NewMediaType("text/json")
	}

	handle, found := h.typeMap[ct.String()]
	if !found {
		err = fmt.Errorf("Unable to find handler for content type: %s", ct)
		handle = h.failsafeHandler
	}

	return handle, err
}

func (h *EchoErrorHandler) HandleError(err error, c echo.Context) {
	defer func() {
		if r := recover(); r != nil {
			if err, ok := r.(error); !ok {
				h.failsafeHandler.Handle(c, h.castToHttpError(fmt.Errorf("%s", err)))
			} else {
				h.failsafeHandler.Handle(c, h.castToHttpError(err))
			}
		}
	}()

	logger := c.Echo().Logger
	he := h.castToHttpError(err)

	handle, cterr := h.negotiateContentType(c.Request())
	if cterr != nil {
		logger.Errorf("%s", cterr)
	}

	if !c.Response().Committed {
		if c.Request().Method == http.MethodHead { // Issue #608
			err = c.NoContent(he.Code)
		} else {
			err = handle.Handle(c, he)
		}
		if err != nil {
			h.failsafeHandler.Handle(c, h.castToHttpError(err))
		}
	} else {
		logger.Errorf("Error occurred in committed response: %s", he)
	}
}