【发布时间】:2013-08-03 16:54:49
【问题描述】:
我在使用 Node.js v.0.10.12 中的异常对象时遇到问题。
代码:(test.js)
var _ = require('underscore');
var invalidJson = '{ this is bad }';
try {
JSON.parse( invalidJson );
}
catch (exc) {
var keys = Object.keys(exc);
console.log('Exception keys (' + keys.length + '): ', keys);
_.each(exc, function (value, key) {
console.log('exc[' + key + '] = ' + value);
});
throw exc;
}
输出:
Exception keys (0): []
test.js:21
throw exc;
^
SyntaxError: Unexpected token t
at Object.parse (native)
at Object.<anonymous> (test.js:10:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
为什么异常是空对象?
另外,报错是来自test.js:21,其实是在'invalidJson':1。一开始没有捕获异常会得到这个错误消息:
undefined:1
{ this is bad }
^
SyntaxError: Unexpected token t
重新抛出异常时如何“转发”此信息?
【问题讨论】:
-
您在寻找
exc.stack吗?
标签: javascript json node.js exception try-catch