/
exception_handler.ts
376 lines (333 loc) · 9.66 KB
/
exception_handler.ts
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*
* @adonisjs/http-server
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import is from '@sindresorhus/is'
import Macroable from '@poppinss/macroable'
import type { Level } from '@adonisjs/logger/types'
import { parseRange } from './helpers.js'
import * as errors from './exceptions.js'
import type { HttpContext } from './http_context/main.js'
import type { HttpError, StatusPageRange, StatusPageRenderer } from './types/server.js'
/**
* The base HTTP exception handler one can inherit from to handle
* HTTP exceptions.
*
* The HTTP exception handler has support for
*
* - Ability to render exceptions by calling the render method on the exception.
* - Rendering status pages
* - Pretty printing errors during development
* - Transforming errors to JSON or HTML using content negotiation
* - Reporting errors
*/
export class ExceptionHandler extends Macroable {
/**
* Computed from the status pages property
*/
#expandedStatusPages?: Record<number, StatusPageRenderer>
/**
* Whether or not to render debug info. When set to true, the errors
* will have the complete error stack.
*/
protected debug: boolean = process.env.NODE_ENV !== 'production'
/**
* Whether or not to render status pages. When set to true, the unhandled
* errors with matching status codes will be rendered using a status
* page.
*/
protected renderStatusPages: boolean = process.env.NODE_ENV === 'production'
/**
* A collection of error status code range and the view to render.
*/
protected statusPages: Record<StatusPageRange, StatusPageRenderer> = {}
/**
* Enable/disable errors reporting
*/
protected reportErrors: boolean = true
/**
* An array of exception classes to ignore when
* reporting an error
*/
protected ignoreExceptions: any[] = [
errors.E_HTTP_EXCEPTION,
errors.E_ROUTE_NOT_FOUND,
errors.E_CANNOT_LOOKUP_ROUTE,
errors.E_HTTP_REQUEST_ABORTED,
]
/**
* An array of HTTP status codes to ignore when reporting
* an error
*/
protected ignoreStatuses: number[] = [400, 422, 401]
/**
* An array of error codes to ignore when reporting
* an error
*/
protected ignoreCodes: string[] = []
/**
* Expands status pages
*/
#expandStatusPages() {
if (!this.#expandedStatusPages) {
this.#expandedStatusPages = Object.keys(this.statusPages).reduce(
(result, range) => {
const renderer = this.statusPages[range as StatusPageRange]
result = Object.assign(result, parseRange(range, renderer))
return result
},
{} as Record<number, StatusPageRenderer>
)
}
return this.#expandedStatusPages
}
/**
* Forcefully tweaking the type of the error object to
* have known properties.
*/
#toHttpError(error: unknown): HttpError {
const httpError: any = is.object(error) ? error : new Error(String(error))
if (!httpError.message) {
httpError.message = 'Internal server error'
}
if (!httpError.status) {
httpError.status = 500
}
return httpError
}
/**
* Error reporting context
*/
protected context(ctx: HttpContext): any {
const requestId = ctx.request.id()
return requestId
? {
'x-request-id': requestId,
}
: {}
}
/**
* Returns the log level for an error based upon the error
* status code.
*/
protected getErrorLogLevel(error: HttpError): Level {
if (error.status >= 500) {
return 'error'
}
if (error.status >= 400) {
return 'warn'
}
return 'info'
}
/**
* A boolean to control if errors should be rendered with
* all the available debugging info.
*/
protected isDebuggingEnabled(_: HttpContext): boolean {
return this.debug
}
/**
* Returns a boolean by checking if an error should be reported.
*/
protected shouldReport(error: HttpError): boolean {
if (this.reportErrors === false) {
return false
}
if (this.ignoreStatuses.includes(error.status)) {
return false
}
if (error.code && this.ignoreCodes.includes(error.code)) {
return false
}
if (this.ignoreExceptions.find((exception) => error instanceof exception)) {
return false
}
return true
}
/**
* Renders an error to JSON response
*/
async renderErrorAsJSON(error: HttpError, ctx: HttpContext) {
if (this.isDebuggingEnabled(ctx)) {
const { default: Youch } = await import('youch')
const json = await new Youch(error, ctx.request.request).toJSON()
ctx.response.status(error.status).send(json.error)
return
}
ctx.response.status(error.status).send({ message: error.message })
}
/**
* Renders an error to JSON API response
*/
async renderErrorAsJSONAPI(error: HttpError, ctx: HttpContext) {
if (this.isDebuggingEnabled(ctx)) {
const { default: Youch } = await import('youch')
const json = await new Youch(error, ctx.request.request).toJSON()
ctx.response.status(error.status).send(json.error)
return
}
ctx.response.status(error.status).send({
errors: [
{
title: error.message,
code: error.code,
status: error.status,
},
],
})
}
/**
* Renders an error to HTML response
*/
async renderErrorAsHTML(error: HttpError, ctx: HttpContext) {
if (this.isDebuggingEnabled(ctx)) {
const { default: Youch } = await import('youch')
const html = await new Youch(error, ctx.request.request).toHTML({
cspNonce: 'nonce' in ctx.response ? ctx.response.nonce : undefined,
})
ctx.response.status(error.status).send(html)
return
}
ctx.response.status(error.status).send(`<p> ${error.message} </p>`)
}
/**
* Renders the validation error message to a JSON
* response
*/
async renderValidationErrorAsJSON(error: HttpError, ctx: HttpContext) {
ctx.response.status(error.status).send({
errors: error.messages,
})
}
/**
* Renders the validation error message as per JSON API
* spec
*/
async renderValidationErrorAsJSONAPI(error: HttpError, ctx: HttpContext) {
ctx.response.status(error.status).send({
errors: error.messages.map((message: any) => {
return {
title: message.message,
code: message.rule,
source: {
pointer: message.field,
},
meta: message.meta,
}
}),
})
}
/**
* Renders the validation error as an HTML string
*/
async renderValidationErrorAsHTML(error: HttpError, ctx: HttpContext) {
ctx.response
.status(error.status)
.type('html')
.send(
error.messages
.map((message: any) => {
return `${message.field} - ${message.message}`
})
.join('<br />')
)
}
/**
* Renders the error to response
*/
renderError(error: HttpError, ctx: HttpContext) {
switch (ctx.request.accepts(['html', 'application/vnd.api+json', 'json'])) {
case 'application/vnd.api+json':
return this.renderErrorAsJSONAPI(error, ctx)
case 'json':
return this.renderErrorAsJSON(error, ctx)
case 'html':
default:
return this.renderErrorAsHTML(error, ctx)
}
}
/**
* Renders the validation error to response
*/
renderValidationError(error: HttpError, ctx: HttpContext) {
switch (ctx.request.accepts(['html', 'application/vnd.api+json', 'json'])) {
case 'application/vnd.api+json':
return this.renderValidationErrorAsJSONAPI(error, ctx)
case 'json':
return this.renderValidationErrorAsJSON(error, ctx)
case 'html':
default:
return this.renderValidationErrorAsHTML(error, ctx)
}
}
/**
* Reports an error during an HTTP request
*/
async report(error: unknown, ctx: HttpContext) {
const httpError = this.#toHttpError(error)
if (!this.shouldReport(httpError)) {
return
}
if (typeof httpError.report === 'function') {
httpError.report(httpError, ctx)
return
}
/**
* Log the error using the logger
*/
const level = this.getErrorLogLevel(httpError)
ctx.logger.log(
level,
{
...(level === 'error' || level === 'fatal' ? { err: httpError } : {}),
...this.context(ctx),
},
httpError.message
)
}
/**
* Handles the error during the HTTP request.
*/
async handle(error: unknown, ctx: HttpContext) {
const httpError = this.#toHttpError(error)
/**
* Self handle exception
*/
if (typeof httpError.handle === 'function') {
return httpError.handle(httpError, ctx)
}
/**
* Handle validation error using the validation error
* renderers
*/
if (httpError.code === 'E_VALIDATION_ERROR' && 'messages' in httpError) {
return this.renderValidationError(httpError, ctx)
}
/**
* Render status page
*/
const statusPages = this.#expandStatusPages()
if (this.renderStatusPages && statusPages[httpError.status]) {
const statusPageResponse = await statusPages[httpError.status](httpError, ctx)
/**
* Use return value and convert it into a response
*/
if (
statusPageResponse !== undefined && // Return value is explicitly defined
!ctx.response.hasLazyBody && // Lazy body is not set
statusPageResponse !== ctx.response // Return value is not the instance of response object
) {
return ctx.response.safeStatus(httpError.status).send(statusPageResponse)
}
return statusPageResponse
}
/**
* Use the format renderers.
*/
return this.renderError(httpError, ctx)
}
}