Skip to content

Improve exception stack trace output (perhaps expose VM filename and lineOffset options?) #18

@mtmacdonald

Description

@mtmacdonald

Hello, thanks for the great package. I would like to request an improvement to how the package handles stack traces when the imported script throws an exception during execution. In my current usage (importFromString without --experimental-vm-modules enabled, i.e. the one that falls back on requireFromString internally), if my imported string throws an exception, the stack trace is unhelpful because:

  • the filename defaults to evalmachine.<anonymous>
  • the line numbers are wrong because module-from-string prepends its own code and also seems to reformat the input string

Is it possible to please improve the stack traces?

One idea/suggestion I have for this is to expose more options from vm.runInNewContext to make this possible, particularly the filename and lineOffset options. I mean roughly like this (then the usages have more control over displaying a meaningful stack trace, although I'm not quite sure how to handle the line offsets given the reformatting of the input - perhaps you could also provide an option to preserve original formatting):

  it('script throws error', () => {
    const context = {
      payload: {foo: 123}
    };
    const migration = `
      const foo = 123;
      const migration = (payload) => {
        throw new Error("bad")
      };
    `;
    vm.runInNewContext(`${migration} migration(payload)`, context, {
      filename: 'real-migration-filename.js',
      lineOffset: 0
    });
  })
bad
real-migration-filename.js:4
        throw new Error("bad")
        ^

Error: bad
    at migration (real-migration-filename.js:104:15)
    at real-migration-filename.js:106:6
    at Script.runInContext (vm.js:144:12)
    at Script.runInNewContext (vm.js:149:17)

What do you think?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions