In my code, I am reading the contents of a file, expecting it to be JSON, parsing it, and printing out the result:
'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));
If the file does not contain JSON, but contains the text "Hello", I receive this error message:
[SyntaxError: Unexpected token H]
To provide more context in the error message, particularly including the file name, I made the following adjustment:
'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));
As a result, the error message now includes the file name:
[SyntaxError: File /tmp/x: Unexpected token H]
It seems to work as intended, but I am new to JavaScript programming. So, I would like to ask: is this the correct way to add context to an Error object?