console.log('See? We can use Errors without using try statements.');
} else {
console.log(dirs);
}
});
最后,在rejecting promises时也可以使用Error对象。这使得它更容易处理promise rejections:
new Promise(function(resolve, reject) {
reject(new Error('The promise was rejected.'));
}).then(function() {
console.log('I am an error.');
}).catch(function(err) {
if (err instanceof Error) {
console.log('The promise was rejected with an error.');
console.log('Error Message: ' + err.message);
}
});
操纵堆栈跟踪
上面啰嗦了那么多,压轴的重头戏来了,那就是如何操纵堆栈跟踪。
本章专门针对那些像NodeJS支Error.captureStackTrace的环境。
Error.captureStackTrace函数接受一个object作为第一个参数,第二个参数是可选的,接受一个函数。capture stack trace 捕获当前堆栈跟踪,并在目标对象中创建一个stack属性来存储它。如果提供了第二个参数,则传递的函数将被视为调用堆栈的终点,因此堆栈跟踪将仅显示调用该函数之前发生的调用。
让我们用例子来说明这一点。首先,我们将捕获当前堆栈跟踪并将其存储在公共对象中。
const myObj = {};
function c() {
}
function b() {
// Here we will store the current stack trace into myObj
Error.captureStackTrace(myObj);
c();
}
function a() {
b();
}
// First we will call these functions
a();
// Now let's see what is the stack trace stored into myObj.stack
console.log(myObj.stack);
// This will print the following stack to the console:
// at b (repl:3:7) <-- Since it was called inside B, the B call is the last entry in the stack
// at a (repl:2:1)
// at repl:1:1 <-- Node internals below this line
// at realRunInThisContextScript (vm.js:22:35)
// at sigintHandlersWrap (vm.js:98:12)
// at ContextifyScript.Script.runInThisContext (vm.js:24:12)
// at REPLServer.defaultEval (repl.js:313:29)
// at bound (domain.js:280:14)
// at REPLServer.runBound [as eval] (domain.js:293:12)
// at REPLServer.onLine (repl.js:513:10)
不知道你注意到没,我们首先调用了a(a入栈),然后我们a中又调用了b(b入栈且在a之上)。然后在b中我们捕获了当前堆栈记录并将其存储在myObj中。因此在控制台中才会按照b a的顺序打印堆栈。
现在让我们给Error.captureStackTrace传递一个函数作为第二个参数,看看会发生什么:
const myObj = {};
function d() {
(责任编辑:admin)