module-deps icon indicating copy to clipboard operation
module-deps copied to clipboard

How to retrieve the file where an error occurred?

Open ericmorand opened this issue 6 years ago • 3 comments

I'm trying to retrieve the file where an error occurred and all I'm able to catch is a standard JavaScript error with a message but not file.

For example:

index.js

const mdeps = require('module-deps');
const md = mdeps();

md.on('error', (e) => {
    console.warn(e);
});
md.end({ file:'./main.js' });

main.js

require('./partial'); // ./partial exists

require('unknown'); // unknown doesn't

The error thrown is:

Error: Cannot find module 'unknown' from '/home/ericmorand/Projects/module-deps-test'

Except by parsing the error message, which is not a serious option - and even this way I would not be able to get the file name, I can't find a way to retrieve the file where the error happened.

I thought that I would be able to catch the correct file by registering to the file event like this:

const mdeps = require('module-deps');
const md = mdeps();

let currentFile;

md.on('file', (file) => {
    currentFile = file;
});
md.on('error', (e) => {
    console.warn(currentFile); // will print ./partial

    console.warn(e);
});
md.end({ file:'./main.js' });

But the currentFile contains ./partial.js because it is the latest file encountered successfully by module-deps. And it is not where the error happens.

Can someone point me to the solution?

ericmorand avatar Nov 25 '19 09:11 ericmorand

I don't think we have a way to do this right now, but i'd be open to adding info properties like .specifier ('unknown') and .source ('module-deps-test/main.js') or something to resolution errors to make them more useful.

goto-bus-stop avatar Nov 25 '19 09:11 goto-bus-stop

That would be awesome. Is it a big change?

ericmorand avatar Nov 25 '19 09:11 ericmorand

no we basically just need some property assignments here in the if (!file) branch: https://github.com/browserify/module-deps/blob/45ad7b641277a3a702fccab70b2b3e19e9d2cc3d/index.js#L180-L185

goto-bus-stop avatar Dec 13 '19 09:12 goto-bus-stop