如何在没有try/catch块的情况下使用异步lambda,并且仍然存在自定义错误消息? [英] How can I use async lambdas without a try/catch block and still have custom error messages?
问题描述
我正在尝试避免将所有等待的调用都包装在带有try catch的异步lambda中.我想捕获并发送自定义错误响应,但是与 .catch()
相比,将每个等待的调用包装在try/catch中在语法上很难看.有没有办法做这样的事情:
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)
});
是否没有像这样包装在try/catch中?
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
}
一旦您在一个lambda中有7个等待的呼叫,就很难尝试一堆.
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()
?
推荐答案
.catch()
方法与 async
/ await
兼容,并且如果要抛出异常,通常不会那么难看.我认为您正在寻找
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;
}
};
这篇关于如何在没有try/catch块的情况下使用异步lambda,并且仍然存在自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!