异步/等待错误处理

Joã*_*eto 5 javascript error-handling node.js promise async-await

我正在尝试处理我的方法引发的自定义错误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)

有人能帮我吗?

我还查看了其他主题:

使用 Async/Await 的正确 Try...Catch 语法

如何在 async/await 情况下正确实现错误处理

HMR*_*HMR 1

函数 findOneAndUpdate 返回一个承诺,因此不需要回调。如果需要回调并且您无法更新到较新的版本,则可以将调用包装在承诺中(在 下To use a callback api as promise you can do:

然后你想设置错误代码,你不能用构造函数来做到这一点。

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

  const result =   await model.findOneAndUpdate({ id: tap.id }, tap);
  if (!result) {
    const e = new Error('Tap doesn\'t exists');
    e.code = 404;
    throw(e);
  }
  return result;
}

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)