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?
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.
function CustomException(message) { const error = new Error(message); return error; } CustomException. prototype = Object. create(Error. prototype);
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With