【问题标题】:JavaScript Exceptions: What's the deal?JavaScript 异常:有什么关系?
【发布时间】: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


【解决方案1】:

Object.keys 尊重不可枚举的属性,请使用

var keys = Object.getOwnPropertyNames(exc);

【讨论】:

  • @zra 那么问题出在哪里?有关错误的信息存储在 .stack 和 .message
  • 问题是堆栈跟踪:我仍然不知道错误发生在 JSON 字符串的哪个位置,请在下面查看我自己的答案..
【解决方案2】:

本例中 Exception 的属性为 [ 'stack', 'arguments', 'type', 'message' ]。

剩下的是堆栈跟踪。 'stack' 是一个字符串:

SyntaxError: Unexpected token t
    at Object.parse (native)
    at Object.<anonymous> (test.js:10:7)

.....

这是使用 try {} catch {} 捕获异常时,

但是,如果这个 try/catch 被删除,并留给系统处理,它会输出一个更有帮助的堆栈跟踪:

undefined:1
{ this is bad }

如何使用 try {} catch {} 获取此堆栈跟踪?

【讨论】:

    猜你喜欢
    • 2020-12-06
    • 2012-08-27
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多