I’m trying to use a function as a callback in possibly multiple places. However, I can’t figure out how to make the callback function tell me the real source of the error.
// `throwIfError` is a function that could be used as a callback
// in multiple places.
function throwIfError(err) {
if(err) {
// Some code that will tell me that the error originated from a call
// to `fs.writeFile` in this file (that is, line 13), instead of
// from the internals of the `writeFile` function. After that, it
// will throw the same or a new error so that the program will fail
// early, instead of continuing with the wrong data.
}
}
require('fs').writeFile(
'some_non_existent_directory/test.txt',
'',
throwIfError
);
Somebody suggested this solution:
function throwIfError(err, fromwhere) {
if(err) {
console.log(`Error came from ${fromwhere}`);
}
}
require('fs').writeFile(
'some_non_existent_directory/test.txt',
'',
err => throwIfError(err, 'fs.writeFile')
);
But I don’t like it because:
- You have to manually indicate it. This feels just wrong. There should be a more idiomatic solution for it, just like stack traces.
- This solution will not include the file name/path and the line number.
Is there a solution for this? Or is the only way to define the callback function where it is used (that is, defining it on the call of writeFile
), instead of defining it somewhere else then referencing it?