I have this code which reads the contents of a file, expects it to be json, parses it and prints 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 get this error printed:
[SyntaxError: Unexpected token H]
I want extra context in this error message, specifically I want the file name. I decided to do this:
'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));
And then I get this error message:
[SyntaxError: File /tmp/x: Unexpected token H]
Which is what I want.
But I just made up this approach and I am not an expert javascript programmer ( yet :) ). So my question is: is this the right way to add context to an Error?