-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy patherror.ts
More file actions
26 lines (21 loc) · 887 Bytes
/
error.ts
File metadata and controls
26 lines (21 loc) · 887 Bytes
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
import { ErrorRequestHandler, NextFunction, Request, Response } from 'express'
import { HttpError } from '@crowd/common'
import { ApiRequest } from '.'
export const asyncWrap =
(fn: (req: ApiRequest, res: Response, next: NextFunction) => Promise<void>) =>
(req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req as ApiRequest, res, next)).catch(next)
}
export const errorMiddleware = (): ErrorRequestHandler => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
return (err, req, res, _next) => {
const request = req as ApiRequest
if (err instanceof HttpError) {
request.log.error(err, { statusCode: err.status }, 'HTTP error occurred!')
res.status(err.status).json(err.toJSON())
} else {
request.log.error(err, 'Unknown error occurred!')
res.status(500).send('Internal Server Error')
}
}
}