考虑我们正在使用以下模块:
//buggy-module.js
function asyncFunctionThatCrashes() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let a = bibi.tibi; // Error
resolve('super');
}, 500);
});
}
module.exports = asyncFunctionThatCrashes;
在我们的项目中:
//our-project.js
const asyncFunctionThatCrashes = require('buggy-module');
router.get('/',
async (req, res) => {
try{
const result = await asyncFunctionThatCrashes();
res.status(200).send(result);
} catch (e) {
res.status(500).send(); // this will not happen
}
})
在这种情况下,应用程序崩溃(try...catch
无济于事,因为该错误发生在异步函数中)。
有办法防止崩溃吗?