如何在JavaScript错误中指定“由…引起”?

在我的NodeJS程序中,我parsing了一些用户的JSON文件。

所以我使用:

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

问题是如果json文件格式不正确,抛出的错误是:

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

因为它不是真正用户友好的,我想抛出一个Error指定一些用户友好的消息(如“你的configuration文件格式不正确”),但我想保留堆栈跟踪,以指向有问题的一行。

在Java世界中,我使用throw new Exception("My user friendly message", catchedException) ,以便有原来的exception,造成这一个。

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; } 

Joyent发布了一个Node.js包,可以完全使用它。 它被称为VError 。 我粘贴一个如何使用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); }); 

会打印以下内容:

 stat "/nonexistent": ENOENT, stat '/nonexistent' 
 try { this.config = JSON.parse(fs.readFileSync(path)); } catch (e) { throw new Error("User friendly message"); } 

使用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/

更新:如果你真的觉得需要自定义错误,你可以定义自己的:

 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/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error提供了大量有用的信息