Skip to content

[Feature]: Print error.cause #11935

@conartist6

Description

@conartist6

🚀 Feature Proposal

The proposal for error.cause is currently stage 3. This proposal is to support jest printing chains of cause properties if they are present on errors.

Motivation

Nested errors can be critical to debugging. JSON.parse might throw a syntax error when reading a file. But if the filename isn't hardcoded in the stack from that called JSON.parse, a developer debugging would have no idea which particular file could not be parsed. The solution is to support chains of causally related errors: as errors bubble up through layers of code they can be caught and rethrown as a cause, allowing additional information to be captured.

Example

Imagine the application contains this code

const readJson = (path) => {
  try {
    const json = JSON.parse(fs.readFileSync(path));
  } catch (e) {
    throw new Error(`Failed to parse JSON from ${path}`, {cause: e});
  }
}

If the application throws during testing complete information is available about the problem. The code throws an error with a cause property defined, per the spec. The cause contains critical information about what the error is, but if jest does not opt in to printing it that information is only present in interactive environments for those who know to look for it. Currently jest would print

Error: Failed to parse JSON from 'path/to/file'.
  at readJson:5

If this feature is implemented jest would print:

Error: Failed to parse JSON from 'path/to/file'.
  at readJson:5
Caused by: SyntaxError: Unexpected token u in JSON at position 0
  at JSON.parse (<anonymous>)
  at readJson:3

Pitch

Jest has the ability to bring the improved debuggability that this proposal creates to a large audience. It is relevant and stable enough for inclusion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions