TritonDataCenter / node-verror

Rich JavaScript errors
MIT License
1.18k stars 61 forks source link

Iterate over nested causes #54

Open chudley opened 6 years ago

chudley commented 6 years ago

VError's cause mechanism is extremely useful for keeping track of an error's potentially nested reason for existing. It's possible to explore this nested structure with the VError.errorForEach() method, which will take the appropriate action depending on the cause (i.e. loop over each error in a MultiError, return the single error if it's a VError, etc.)

It would be great if node-verror could provide a mechanism for iteratively exploring a nested VError so that a consumer can exhaustively display each of the causes of a VError chain in a way that suits them.

A use case I've been working on recently is to have a CLI tool print a human-friendly message to the terminal in the event of failure, where the cause of the failure is a nested set of VErrors and/or MultiErrors. Having the CLI tool print the top-level error would mask much of the detail below if any of the causes are a MultiError (the message would contain the "first of 3 errors: ..." summary), but all of it is useful.

chudley commented 6 years ago

I've created an example in this gist which can be dropped into the "experiments/" folder of a working node-verror project to try out. Note that it's making use of WError to prevent repeated "first of 3 errors: ..." messages on parent-level VErrors, which is potentially a stretch given WErrors documented use case.

I wanted to ping it here for early discussion (in lieu of writing tests) before heading to Gerrit because there's the potential to have the existing VError.errorForEach() method simply make use of this new VError.errorForEachIter() function with a depth of 1, or possibly even have VError.errorForEach() do the iteration itself but default to 1 for backwards compatibility.

jcheroske commented 5 years ago

I've just run into this exact thing. I can implement the recursion myself, but it would be super cool if the library had a tree traversal function.