[英]how to solve UnhandledPromiseRejectionWarning?
I recently learnt javascript and I have trouble with understanding the Promise concept.我最近学习了 javascript,但在理解 Promise 概念时遇到了麻烦。 Here is a snippet for which I would expect an exception to occur.
这是一个片段,我希望会发生异常。
async function testRepository(): Promise<void> {
throw new Error('error');
};
async function testService(): Promise<void> {
try {
return await testRepository();
} catch (err) {
throw err;
}
};
async function testController(): Promise<void> {
try {
return await testService();
} catch (err) {
throw err;
}
}
(async () => {
try {
console.log(await testController());
} catch (err) {
throw err;
}
})();
When running tat code, I get the following error message:运行 tat 代码时,我收到以下错误消息:
(node:16670) UnhandledPromiseRejectionWarning: Error: error
at /home/pellegrini/temp/webservices/test.js:42:19
at step (/home/pellegrini/temp/webservices/test.js:33:23)
at Object.next (/home/pellegrini/temp/webservices/test.js:14:53)
at /home/pellegrini/temp/webservices/test.js:8:71
at new Promise (<anonymous>)
at __awaiter (/home/pellegrini/temp/webservices/test.js:4:12)
at testRepository (/home/pellegrini/temp/webservices/test.js:40:12)
at /home/pellegrini/temp/webservices/test.js:54:42
at step (/home/pellegrini/temp/webservices/test.js:33:23)
at Object.next (/home/pellegrini/temp/webservices/test.js:14:53)
(node:16670) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:16670) [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.
Could you tell me what is wrong with that code and to make it work.你能告诉我那个代码有什么问题并让它工作吗? By working I mean generating an Error as I would expect if I understand right the concept of Promise.
通过工作,我的意思是如果我正确理解 Promise 的概念,就会产生我期望的错误。
The issue is that you keep re-throwing the error, and don't ever handle it anywhere.问题是您不断地重新抛出错误,并且永远不会在任何地方处理它。 So it bubbles out and out and out, until it generates an UnhandledPromiseRejectionWarning.
所以它不断地冒泡,直到它产生一个 UnhandledPromiseRejectionWarning。
You just need to break this chain at some point, by handling the error.你只需要在某个时候通过处理错误来打破这个链条。 For example:
例如:
async function testService(): Promise<void> {
try {
return await testRepository();
} catch (err) {
console.log('got an error');
//throw err; // Don't re-throw
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.