Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a "caused by" in a JavaScript Error?

In my NodeJS program, I parse some user JSON file.

So I use :

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

The problem is that if the json file is not correctly formated, the error thrown is like:

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) ... 

As it is not really user friendly I would like to throw an Error specifying some user friendly message (like "your config file is not well formated") but I want to keep the stacktrace in order to point to the problematic line.

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

How is it possible in the JS world?

like image 729
Anthony O. Avatar asked Sep 10 '14 11:09

Anthony O.


People also ask

How do you code error in JavaScript?

JavaScript try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

How do you create a new error in JavaScript?

function CustomException(message) { const error = new Error(message); return error; } CustomException. prototype = Object. create(Error. prototype);

What is the most common error in JavaScript?

TypeError is one of the most common errors in JavaScript apps. This error is created when some value doesn't turn out to be of a particular expected type. Some of the common cases when it occurs are: Invoking objects that are not methods.


1 Answers

What I finally did is:

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; } 
like image 63
Anthony O. Avatar answered Oct 14 '22 01:10

Anthony O.