【问题标题】:Koa - Error handling within built-in function and async/awaitKoa - 内置函数和异步/等待中的错误处理
【发布时间】:2020-12-19 23:10:33
【问题描述】:

在我的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');
};

我明白了……

哦哦:测试

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

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

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

错误:测试 在 Response.s3.createMultipartUpload ....

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

【问题讨论】:

    标签: javascript node.js error-handling async-await koa


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-18
      • 2016-12-28
      • 2018-07-29
      • 2017-05-25
      • 2022-01-09
      • 2018-04-06
      • 2018-11-12
      • 1970-01-01
      相关资源
      最近更新 更多