Search code examples
javascriptnode.jserror-handlingasync-awaitkoa

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


In my app.js I have the following...

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());

Then in routes I have defined...

router.post('/', retrieve);

If I throw an error inside of retrieve it will bubble up to app.js, for example...

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

I get...

Uh oh: test

Now let's say I have a function like this and I want to throw an error...

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

It will not bubble up to app.js, instead it will show the following...

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

Why doesn't this get bubbled up to app.js? How can I do so?


Solution

  • The way I solved it was by using the promise format...

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