Koa - 内置函数中的错误处理和 async/await

Koa - Error handling within built-in function and async/await

在我的 app.js 我有以下...

app.use(async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    ctx.status = 400
    ctx.body = `Uh-oh: ${err.message}`
    console.log('Error handler:', err.message)
  }
});

app.use(router());

然后在我定义的路线中...

router.post('/', retrieve);

如果我在 retrieve 中抛出一个错误,它将冒泡到 app.js,例如...

const retrieve = async ctx => {
  throw new Error('test');
};

我明白了...

Uh oh: test

现在假设我有一个这样的函数,我想抛出一个错误...

const retrieve = async ctx => {
  await s3.createMultipartUpload({
    Bucket: "test",
    Key: "testName",
    ContentType: "contentType"
  }, (err, mpart) => {
    throw new Error("test");
  });
}

它不会冒泡到 app.js,而是显示以下内容...

Error: test at Response.s3.createMultipartUpload ....

为什么这不会冒泡到 app.js?我该怎么做?

我解决它的方法是使用 promise 格式...

await s3.createMultipartUpload({
  Bucket: "test",
  Key: "testName",
  ContentType: "contentType"
})
.promise()
.then(data => {
  //Do Stuff
}).catch(err => { throw new Error('test') });