向Javascript错误添加上下文

时间:2015-10-15 13:44:07

标签: javascript error-handling

我有这个代码读取文件的内容,期望它是json,解析它并打印出结果:

'use strict';

const fs = require('fs');
const Promise = require("bluebird");
Promise.promisifyAll(fs);

const printFile = (file) => fs.readFileAsync(file, "utf-8")
  .then((jsonHopefully) => console.log(JSON.parse(jsonHopefully)))
  ;

printFile("/tmp/x")
  .catch( (error) => console.log(error));

如果文件不包含json,但包含文本Hello,则会出现此错误:

[SyntaxError: Unexpected token H]

我想在此错误消息中添加额外的上下文,特别是我想要文件名。我决定这样做:

'use strict';

const fs = require('fs');
const Promise = require("bluebird");
Promise.promisifyAll(fs);

const printFile = (file) => fs.readFileAsync(file, "utf-8")
  .then((jsonHopefully) => console.log(JSON.parse(jsonHopefully)))
  .catch( error => {
    error.message = "File " + file + ": " + error.message;
    throw error;
  })
  ;

printFile("/tmp/x")
  .catch( (error) => console.log(error));

然后我收到此错误消息:

[SyntaxError: File /tmp/x: Unexpected token H]

这就是我想要的。

但我只是编造了这种方法而且我不是专业的javascript程序员(还是:))。所以我的问题是:这是向错误添加上下文的正确方法吗?

1 个答案:

答案 0 :(得分:0)

您也可以直接引发错误

 throw Error("Bogus error to test error, ${someParameters} are observed.")

我不会直接编辑错误消息