How can I use async lambdas without a try/catch block and still have custom error messages?

前提是你 提交于 2021-01-29 15:21:02

问题


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


回答1:


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;
  }
};


来源:https://stackoverflow.com/questions/60046674/how-can-i-use-async-lambdas-without-a-try-catch-block-and-still-have-custom-erro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!