Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript Exceptions: What's the deal?

JavaScript Exceptions: What's the deal?

Problem

I am having trouble working with Exception Objects in Node.js v.0.10.12.

The code: (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;
}

The output:

Exception keys (0):  []

test.js:21
    throw exc;
          ^
SyntaxError: Unexpected token t
    at Object.parse (native)
    at Object. (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

Why is the exception an empty object?

Additionally, the error is reported to come from test.js:21, but in fact is in 'invalidJson':1. Not catching the exception in the first place gets this error message instead:

undefined:1
{ this is bad }
  ^
SyntaxError: Unexpected token t

How can I 'forward' this information when re-throwing the exception?

Problem courtesy of: zra

Solution

The properties of the Exception in this case are [ 'stack', 'arguments', 'type', 'message' ].

What's left is the Stack Trace. 'stack' is a string:

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

.....

This is when the exception is caught using try {} catch {},

however if this try/catch is removed, and left for the system to process, it outputs a much more helpful stack trace:

undefined:1
{ this is bad }

how can I get this stack trace using try {} catch {} ?

Solution courtesy of: zra

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

JavaScript Exceptions: What's the deal?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×