如何指定“由...引起”在JavaScript错误? [英] How to specify a "caused by" in a JavaScript Error?
问题描述
在我的NodeJS程序中,我解析了一些用户JSON文件。
In my NodeJS program, I parse some user JSON file.
所以我使用:
this.config = JSON.parse(fs.readFileSync(path));
问题是如果json文件没有正确格式化,抛出的错误就像:
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.
在Java世界中,我使用抛出新的异常(我的用户友好消息,catchedException)
,以便获得导致该异常的原始异常。
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.
JS世界怎么可能?
推荐答案
我最后做的是:
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;
}
这篇关于如何指定“由...引起”在JavaScript错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!