【发布时间】:2022-07-22 00:04:25
【问题描述】:
我有一个在 catch 块中不起作用的错误记录器。通过调用 function1 并使用记录器抛出错误(记录器在保存到数据库后抛出错误),它只会被中间件过滤器(捕获错误并在响应中发送)在 try...catch 之外捕获块。
代码:
class ErrorLogger {
constructor() {}
async error(error: CustomError | Error) {
await this.saveError(error); //saves the error in the db
throw error;
}
}
const messageCodes = [
{
'not:found': {
type: 'BadRequest',
httpStatus: HttpStatus.BAD_REQUEST, //from @nestjs/common ( = 400 )
errorMessage: 'something not found.',
}
}
]
class CustomError extends Error () {
constructor(messageCode) {
super();
this.httpStatus = messageCodes[messageCode].httpStatus;
this.messageCode = messageCodes[messageCode].messageCode;
this.errorMessage = messageCodes[messageCode].errorMessage;
}
}
async function logic(param): void {
if(param !== "c") {
throw new CustomError('not:found');
}
}
// this is an endpoint
async function function1(param) {
const errorLogger = new ErrorLogger();
if(param !== "b") {
await errorLogger.error(new CustomError('not:found'));
// if this error is thrown, request will return an object like this:
// {
// statusCode: 400,
// message: "something not found"
// }
// this is a format yielded by some error filtering middleware
}
try {
await logic(param);
} catch(e: CustomError) {
await errorLogger.error(e);
// this will appear as { "message": "Internal Server Error" }
}
}
关于如何解决这个问题的任何建议? (打字稿/嵌套)
【问题讨论】:
标签: javascript node.js typescript nest