0

I'm trying to avoid wrapping all my awaited calls in an async lambda with a try catch. I want to catch and send custom error responses, but wrapping each awaited call in a try/catch is syntactically ugly compared to .catch(). Is there a way to do something like this:

exports.hanlder = async (event, context, callback) => {
  const foo = await bar(baz).catch((error) => {
    eventResponse.statusCode = 503;
    eventResponse.body = JSON.stringify({ message: 'unable to bar' , error});
    // normally we'd callback(null, eventResponse)
  });

Without wrapping in try/catch like this?

exports.hanlder = async (event, context, callback) => {
  let foo;
  try {
    foo = await bar(baz);
  } catch (error) {
     eventResponse.statusCode = 503;
     eventResponse.body = JSON.stringify({ message: 'unable to bar', error});
     return eventResponse;
  }
  // then do something else with foo

  if (foo.whatever) {
     // some more async calls
  }

It's just not pretty to have a bunch of try/catch once you have like 7 awaited calls in a single lambda. Is there a prettier way to do it using the promise built-in .catch()?

FlavorScape
  • 13,301
  • 12
  • 75
  • 117

1 Answers1

3

The .catch() method is compatible with async/await and often less ugly if you want to rethrow an exception. I think you're looking for

exports.handler = async (event, context, callback) => {
  try {
    const foo = await bar(baz).catch(error => {
      throw {message: 'unable to bar', error};
    });
    // do something with `foo`, and more `await`ing calls throwing other errors
    // return a response
  } catch(err) {
    eventResponse.statusCode = 503;
    eventResponse.body = JSON.stringify(err);
    return eventResponse;
  }
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • ah great, don't know why i totally forgot I could just re-throw it. Then I assume the lambda just makes the error message the response content. – FlavorScape Feb 03 '20 at 20:37
  • Yes, I would've expected that, I just wasn't sure whether your goal was to set a custom status code etc as well. You might be able to omit the `try`/`catch` block and just let the lamda runner handle the error. – Bergi Feb 03 '20 at 20:40
  • dang, i think i have to still use the try / catch. if i just throw with the intended message, i get the 'unhandled promise rejection'. – FlavorScape Feb 03 '20 at 20:42
  • 1
    @FlavorScape Aw, I would've hoped for more in a lambda, but you still can [use your own wrapper](https://stackoverflow.com/q/41349331/1048572) to deal with the error handling so that you just write `exports.handler = handleErrors(async(event, context) { … });` – Bergi Feb 03 '20 at 20:45
  • yeah you'd think they'd just internally have re-thrown errors emit the response with the message of the re-thrown error, just as the callback does.... sigh – FlavorScape Feb 03 '20 at 21:10