-
Notifications
You must be signed in to change notification settings - Fork 729
Expand file tree
/
Copy patherrorHandler.ts
More file actions
74 lines (67 loc) · 2.08 KB
/
Copy patherrorHandler.ts
File metadata and controls
74 lines (67 loc) · 2.08 KB
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
import type { ErrorRequestHandler, NextFunction, Request, Response } from 'express'
import {
InsufficientScopeError as Auth0InsufficientScopeError,
UnauthorizedError as Auth0UnauthorizedError,
} from 'express-oauth2-jwt-bearer'
import { HttpError, InsufficientScopeError, InternalError, UnauthorizedError } from '@crowd/common'
import { SlackChannel, SlackPersona, sendSlackNotification } from '@crowd/slack'
/**
* Converts errors to structured JSON: `{ error: { code, message } }`.
* Defaults to 500 Internal Error for unhandled errors.
*/
export const errorHandler: ErrorRequestHandler = (
error: any,
req: Request,
res: Response,
_next: NextFunction,
) => {
if (error instanceof HttpError) {
res.status(error.status).json(error.toJSON())
return
}
if (error instanceof Auth0InsufficientScopeError) {
const httpErr = new InsufficientScopeError(error.message || undefined)
res.status(httpErr.status).json(httpErr.toJSON())
return
}
if (error instanceof Auth0UnauthorizedError) {
const httpErr = new UnauthorizedError(error.message || undefined)
res.status(httpErr.status).json(httpErr.toJSON())
return
}
req.log.error(
{
error: { name: error?.name, message: error?.message, stack: error?.stack },
url: req.url,
method: req.method,
query: req.query,
body: req.body,
},
'Unhandled error in public API',
)
sendSlackNotification(
SlackChannel.CDP_ALERTS,
SlackPersona.ERROR_REPORTER,
`Public API Error 500: ${req.method} ${req.url}`,
[
{
title: 'Request',
text: `*Method:* \`${req.method}\`\n*URL:* \`${req.url}\``,
},
{
title: 'Error',
text: `*Name:* \`${error?.name || 'Unknown'}\`\n*Message:* ${error?.message || 'No message'}`,
},
...(error?.stack
? [
{
title: 'Stack Trace',
text: `\`\`\`${error.stack.substring(0, 2700)}\`\`\``,
},
]
: []),
],
)
const unknownError = new InternalError()
res.status(unknownError.status).json(unknownError.toJSON())
}