向 Javascript 错误添加上下文

Mik*_*gan 5 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));
Run Code Online (Sandbox Code Playgroud)

如果文件不包含 json,但包含文本 Hello,我会打印此错误:

[SyntaxError: Unexpected token H]
Run Code Online (Sandbox Code Playgroud)

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

'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));
Run Code Online (Sandbox Code Playgroud)

然后我收到此错误消息:

[SyntaxError: File /tmp/x: Unexpected token H]
Run Code Online (Sandbox Code Playgroud)

这就是我想要的。

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

Nai*_*afa 0

也可以直接抛出错误

 throw Error("Bogus error to test error, ${someParameters} are observed.")
Run Code Online (Sandbox Code Playgroud)

我不会直接编辑错误消息