小编Joã*_*eto的帖子

异步/等待错误处理

我正在尝试处理我的方法引发的自定义错误async,但该try catch块无法正常工作。

我认为我这样做的方式应该有效,但错误没有被捕获,并且程序通过在终端中显示它来终止。

这是抛出错误的地方:

async setupTap(tap) {
  const model = this.connection.model('Tap', TapSchema);

  await model.findOneAndUpdate({ id: tap.id }, tap, (err, result) => {
    let error = null;
    if (!result) {
      throw new Error('Tap doesn\'t exists', 404);
    }
    return result;
  });
}
Run Code Online (Sandbox Code Playgroud)

然后是错误处理代码:

async setupTapHandler(request, h) {
  const tapData = {
    id: request.params.id,
    clientId: request.payload.clientId,
    beerId: request.payload.beerId,
    kegId: request.payload.kegId,
  };

  try {
    await this.kegeratorApi.setupTap(tapData);
  } catch (e) {
    if (e.code === 404) return h.response().code(404);
  }

  return h.response().code(204);
} …
Run Code Online (Sandbox Code Playgroud)

javascript error-handling node.js promise async-await

5
推荐指数
1
解决办法
3264
查看次数