【问题标题】:Nest throw error inside catch block yields在 catch 块中嵌套抛出错误产生
【发布时间】: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


    【解决方案1】:

    只要不抛出 NestJS 特定的异常,每个错误都会导致 500 - Internal Server Error。见here

    【讨论】:

      猜你喜欢
      • 2020-04-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2016-08-15
      • 2017-01-14
      • 2017-06-20
      • 2019-05-20
      • 1970-01-01
      相关资源
      最近更新 更多