Adding context to Javascript Errors
Asked Answered
L

2

6

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?

Longish answered 15/10, 2015 at 13:44 Comment(1)
This might be a better fit for codereview.stackexchange.comKino
J
0

You can also directly throw the error

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

I would not edit the error message directly

Jungle answered 11/6, 2019 at 14:56 Comment(0)
D
0

You can add some context like error code or any additional data within the cause property of the option object:

throw new Error(`Unknown market ${market}`, {
  cause: { code: 'INVALID_MARKET', market, someArray: [1, 2], ...moreStructuralData },
})

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause#providing_structured_data_as_the_error_cause

Distracted answered 4/6, 2024 at 10:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.