I am primarily from a Java background (and hence a Java mindset) so I'm not sure if I'm making any sense here.
I'm trying to find the correct way to log an error (thrown somewhere higher in the stack, caught via a lower-level generic catch block later) into the browser's web console, while displaying correct stacktrace information in a nice collapsible way. The following is an example, from the Slack chat web client running on Firefox:
As you can see, by default only the error message is displayed (first log), with a collapsible arrow icon in front which, when clicked, expands the full stacktrace (second log). Pretty neat, I would say.
This is what I have tried:
Creating an error inside a nested function call:
h = () => TypeError("b"); g = () => h(); f = () => g(); e = f(); The resulting error object is now stored in e.
e, when passed to console.error(), does show a collapsed stacktrace, but apparently it reflects the invocation location of console.error() itself (the trace has just a single <anonymous> debugger eval code line), in addition to a non-collapsible copy of the correct stacktrace (containing the f, g and h functions):
Collapsed (default) view, which still shows the (correct) stacktrace:
Expanded view, showing two stacktraces (with the now-expanded 'wrong' stacktrace at the bottom):
Alternatively, if I do something like:
h = () => { throw TypeError("b"); } g = () => h(); f = () => g(); e = f(); I just get a one-liner without a stacktrace:
(Note.: Chrome seems to behave differently here, giving out something similar to console.error(e); in that case, both stacktraces are correct ones, but still there are two traces, one being non-collapsible.)
If I do the console.error() only using a message text, in-place (right where the error is supposed to originate):
h = () => { console.error("b"); } g = () => h(); f = () => g(); e = f(); I see the expected behaviour:
However, obviously this is not a feasible solution because what I need is to log an arbitrary error (generated somewhere higher in the stack) at a lower-level (say, a master catch block in the original driver function).
h = () => { throw TypeError("b"); } g = () => h(); f = () => g(); try { e = f(); } catch (e) { // expecting to see an error log, with one nice, collapsible stacktrace console.error(e); } One of my colleagues suggested that the proper way to do this might be to override the default console.error() function with my own custom implementation, and that is how Slack might also be doing the magic. Is that the only workaround, or is there a more 'standardized' (and cross-browser) solution that I can use out of the box (preferably without relying on external libraries)?




