I'm experimenting with zones (zone.js) and I realized I don't know what's the best way to print all the zones from root to the current zone that threw an error.
For example this code uses two nested callbacks with setTimeout()
and then calls a function called failedFunc()
that throws an error:
require('zone.js');
function failedFunc() {
throw new Error("it's broken");
}
let rootZone = Zone.current;
function func1() {
let zoneA = rootZone.fork({name: 'zoneA'});
zoneA.run(() => {
setTimeout(() => func2());
});
}
function func2() {
let zoneB = Zone.current.fork({name: 'zoneB'});
zoneB.run(() => {
setTimeout(() => failedFunc());
});
}
func1();
When I run this example it gives the following output:
/.../zone-test/node_modules/zone.js/dist/zone-node.js:170
throw error;
^
Error: it's broken
at new Error (native)
at failedFunc (/.../zone-test/zone_02.js:12:9) [zoneB]
at Timeout.setTimeout (/.../zone-test/zone_02.js:28:22) [zoneB]
at Zone.runTask (/.../zone-test/node_modules/zone.js/dist/zone-node.js:166:47) [<root> => zoneB]
at Timeout.ZoneTask.invoke (/.../zone-test/node_modules/zone.js/dist/zone-node.js:416:38) [<root>]
at Timeout.data.args.(anonymous function) [as _onTimeout] (/.../zone-test/node_modules/zone.js/dist/zone-node.js:1590:25) [<root>]
at ontimeout (timers.js:365:14) [<root>]
at tryOnTimeout (timers.js:237:5) [<root>]
at Timer.listOnTimeout (timers.js:207:5) [<root>]
The correct path for the zone that threw the error is <root>
=> zoneA
=> zoneB
.
However it's not obvious from the output. There's just [root]
and zoneB
and it doesn't mention the zoneA
which is confusing. I guess this is because the zone.js
's monkey patch only adds zone info to the lines in the call stack. So when I'm using setTimeout()
than creating zoneA
doesn't correspond to any line in the output and that's why I don't see it anywhere.
Nonetheless, I can print the path to the current zone by iterating all it's parents but this means I need to know where the error first happened and add the following code to it (which would be very tedious in practice):
function failedFunc() {
let zone = Zone.current;
let zones = [];
while (zone) {
zones.push(zone.name);
zone = zone.parent;
}
console.log(zones);
throw new Error("it's broken");
}
// ...
Now when I run this I'll get what I need:
[ 'zoneB', 'zoneA', '<root>' ]
/.../zone-test/node_modules/zone.js/dist/zone-node.js:170
throw error;
^
Error: it's broken
at new Error (native)
So I'm wondering how to use zone.js in practice and in a way that it's easier than this.
long-stack-trace-zone
so I just pasted it in HTML section.Zone.current
always returns the zone in which it's being run – Etam