问题
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