有以下功能,它不能捕获MyException。
const myFunction = () => async (req, res, next) => {
try {
myHTTPRequest().then(async (response) => {
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
})
.catch((error) => {
throw error; //Doesn't work
});
} catch (error) {
console.log('This block should catch MyException, but it doesn't');
next(error);
}
};
相反,应用程序将以下错误消息写入控制台
(node:45746) UnhandledPromiseRejectionWarning
(node:45746) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:45746) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
问题是,如何调整代码以在预期的Catch-Block中捕获MyException?
答案 0 :(得分:4)
问题在于您正在将.then/.catch
与try/catch
混合使用。
如果您希望代码在try/catch
函数中输入async
,则必须在await
上使用Promise
关键字。
您可以删除.catch
,因为它什么都不做,您再次抛出了错误,这导致UnhandledPromiseRejectionWarning
const myFunction = () => (req, res, next) => {
try {
const response = await myHTTPRequest();
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
} catch (error) {
next(error);
}
};
使用.then/catch
而不使用async/await
的代码将是:
const myFunction = () => (req, res, next) => {
myHTTPRequest().then((response) => {
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
})
.catch((error) => {
throw error;
// It makes no sense to throw again in here
// But I'm showing you how to handle it if you do
})
.catch(error => {
next(error);
})
};
当然,双.catch
没有任何意义,您应该将其删除,只剩下一个:
const myFunction = () => (req, res, next) => {
myHTTPRequest().then((response) => {
if (response.data.results.length != 1) {
throw new MyException('MyError');
}
res.end('All good');
})
.catch(error => {
next(error);
})
};