How to indicate "invoked" in a JavaScript error?

In my NodeJS program, I am parsing some user JSON file.

Therefore, I use:

this.config = JSON.parse(fs.readFileSync(path)); 

The problem is that if the json file is not correctly formed, the error that appears looks like this:

 undefined:55 }, ^ SyntaxError: Unexpected token } at Object.parse (native) at new MyApp (/path/to/docker/lib/node_modules/myApp/lib/my-app.js:30:28) ... 

Since this is not very convenient for the user, I would like to throw Error indicating some user-friendly message (for example, "your configuration file is not very well formed"), but I want to save stacktrace to indicate the problem line.

In the Java world, I used throw new Exception("My user friendly message", catchedException) to have the original exception that caused this.

How is this possible in the JS world?

+7
javascript stack-trace
source share
4 answers

What I finally did:

 try { this.config = JSON.parse(fs.readFileSync(path)); } catch(err) { var newErr = new Error('Problem while reading the JSON file'); newErr.stack += '\nCaused by: '+err.stack; throw newErr; } 
+7
source share

Joyent has released a Node.js package that can be used for just that. It is called VError . I am inserting an example of how you will use pacakge:

 var fs = require('fs'); var filename = '/nonexistent'; fs.stat(filename, function (err1) { var err2 = new VError(err1, 'stat "%s"', filename); console.error(err2.message); }); 

will print the following:

 stat "/nonexistent": ENOENT, stat '/nonexistent' 
+1
source share

Use the try / catch :

 try { this.config = JSON.parse("}}junkJSON}"); //...etc } catch (e) { //console.log(e.message);//the original error message e.message = "Your config file is not well formatted.";//replace with new custom message console.error(e);//raise the exception in the console //or re-throw it without catching throw e; } 

http://jsfiddle.net/0ogf1jxs/5/

UPDATE: If you really feel the need for a special error, you can define its own:

 function BadConfig(message) { this.message = message; this.name = "BadConfig"; } BadConfig.prototype = new Error(); BadConfig.prototype.constructor = BadConfig; try { this.config = JSON.parse("}}badJson}"); } catch(e) { throw new BadConfig("Your JSON is wack!"); } 

http://jsfiddle.net/kL394boo/

A lot of useful information at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error

-one
source share
 try { this.config = JSON.parse(fs.readFileSync(path)); } catch (e) { throw new Error("User friendly message"); } 
-one
source share

All Articles