未处理exception与asynchronous等待
我正在尝试将旧的callback样式函数转换为asynchronous等待。 但是我不明白我怎么能捕获未处理的exception。
例如,让我们说我有一个function
apiCall(input, function(error, result) { if (error) { console.log(error); } else { console.log(result); } });
我转换为Promise
function test1(input) { return new Promise(function(resolve, reject) { apiCall(input, function(err, result) { if (err) { reject(err); } else { resolve(result); } }); }); }
然后我打电话给他
test1(4) .then(function(result) { console.log('Result: ' + result); }) .catch(function(errorr) { console.log('My Error: ' + errorr); });
即使我尝试返回错误,有时这个函数崩溃。 比方说磁盘错误,JSONparsing错误等。我没有处理一些错误。 我只能用这个错误来捕捉这些错误
process.on('uncaughtException', function(error) { console.log('uncaughtException' + error); });
有没有办法让我赶上asynchronous等待的各种错误?
编辑:这里是完整的github回购你试试
https://github.com/tosbaha/promise
运行节点testme.js,看看它崩溃,exception处理程序不运行。
可能会崩溃的文件是这个任何函数可能会崩溃,但我不能预见每一种错误。 这就是为什么我正在寻找一个解决scheme来捕获此文件中的错误。
如果您在node testme.js
repo中运行代码,将会出现以下错误
results[trackingId] = trackingArray.doesntExist.Something; ^ TypeError: Cannot read property 'Something' of undefined
正如你所看到的那样, catch
处理程序不会捕获错误。