2022-04-05 01:37:31 +08:00
|
|
|
import { RenderingMWs } from '../middlewares/RenderingMWs';
|
|
|
|
import { ErrorCodes, ErrorDTO } from '../../common/entities/Error';
|
|
|
|
import { Logger } from '../Logger';
|
|
|
|
import { Express, NextFunction, Request, Response } from 'express';
|
2016-03-26 18:19:10 +08:00
|
|
|
|
2016-05-09 23:04:56 +08:00
|
|
|
export class ErrorRouter {
|
2021-04-18 21:48:35 +08:00
|
|
|
public static route(app: Express): void {
|
2017-06-11 04:32:56 +08:00
|
|
|
this.addApiErrorHandler(app);
|
|
|
|
this.addGenericHandler(app);
|
|
|
|
}
|
2016-03-26 18:19:10 +08:00
|
|
|
|
2021-04-18 21:48:35 +08:00
|
|
|
private static addApiErrorHandler(app: Express): void {
|
2022-04-05 01:37:31 +08:00
|
|
|
app.use('/api/*', RenderingMWs.renderError);
|
2018-03-31 03:30:30 +08:00
|
|
|
}
|
2016-03-26 18:19:10 +08:00
|
|
|
|
2021-04-18 21:48:35 +08:00
|
|
|
private static addGenericHandler(app: Express): void {
|
2022-04-05 01:37:31 +08:00
|
|
|
app.use(
|
|
|
|
(err: any, req: Request, res: Response, next: NextFunction): any => {
|
2020-01-08 05:17:54 +08:00
|
|
|
if (err.name === 'UnauthorizedError') {
|
|
|
|
// jwt authentication error
|
|
|
|
res.status(401);
|
2022-04-05 01:37:31 +08:00
|
|
|
return next(
|
|
|
|
new ErrorDTO(ErrorCodes.NOT_AUTHENTICATED, 'Invalid token')
|
|
|
|
);
|
2020-01-08 05:17:54 +08:00
|
|
|
}
|
2020-12-28 01:57:02 +08:00
|
|
|
if (err.name === 'ForbiddenError' && err.code === 'EBADCSRFTOKEN') {
|
|
|
|
// jwt authentication error
|
|
|
|
res.status(401);
|
2022-04-05 01:37:31 +08:00
|
|
|
return next(
|
|
|
|
new ErrorDTO(
|
|
|
|
ErrorCodes.NOT_AUTHENTICATED,
|
|
|
|
'Invalid CSRF token',
|
|
|
|
err,
|
|
|
|
req
|
|
|
|
)
|
|
|
|
);
|
2020-12-28 01:57:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
console.log(err);
|
2020-01-08 05:17:54 +08:00
|
|
|
|
2018-03-31 03:30:30 +08:00
|
|
|
// Flush out the stack to the console
|
|
|
|
Logger.error('Unexpected error:');
|
2017-07-18 05:12:12 +08:00
|
|
|
console.error(err);
|
2022-04-05 01:37:31 +08:00
|
|
|
return next(
|
|
|
|
new ErrorDTO(
|
|
|
|
ErrorCodes.SERVER_ERROR,
|
|
|
|
'Unknown server side error',
|
|
|
|
err,
|
|
|
|
req
|
|
|
|
)
|
|
|
|
);
|
2017-06-11 04:32:56 +08:00
|
|
|
},
|
|
|
|
RenderingMWs.renderError
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|