-
Notifications
You must be signed in to change notification settings - Fork 1
/
errorHandler.ts
43 lines (37 loc) · 1.35 KB
/
errorHandler.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
import { type Request, type Response, type NextFunction } from 'express'
import { MiddlewareTypes, middleware } from '../util/middleware.js'
import { apiResponse } from '../util/apiResponse.js'
import { ConflictError, ZHTTPError, InternalServerError } from '@zhttp/errors'
import { loggerInstance } from '../util/logger.js'
export const errorHandlerMiddleware = middleware({
name: 'ErrorHandler',
type: MiddlewareTypes.AFTER,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
handler (
originalError: Error,
req: Request,
res: Response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
next: NextFunction
) {
let status = 500
let parsedError = new InternalServerError()
const log = loggerInstance.logger('errorHandler')
if (originalError.name === 'UniqueViolationError') {
status = 409
parsedError = new ConflictError(parsedError.message)
}
if (originalError instanceof ZHTTPError) {
status = originalError.http
parsedError = originalError
}
// log.error(originalError);
if (status >= 500) {
log.error(`🔴 FAIL ${req.method} ${req.originalUrl}`, parsedError)
} else {
log.warn(`⚠️ FAIL ${req.method} ${req.originalUrl}`, parsedError)
}
res.status(status).json(apiResponse({}, { error: parsedError }))
return res.end()
}
})