Using asynchronous darts with stack_trace chaining

I am trying to use the Chain object provided by stack_trace as follows:

import 'dart:async'; import 'package:stack_trace/stack_trace.dart'; main() async { print('Hello world: ${console_test.calculate()}!'); Chain.capture(() async { try { await testFunction(); } catch(e,st) { print(Trace.format(new Chain.forTrace(st))); } }); } Future testFunction() async { throw new Exception("TEST"); } 

The output I get is this:

 Hello world: 42! main.dart 4:1 main.<async>.<fn>.<async> 

I understand that the output stack trace should include testFunction, but for some reason this is not the case. If I do this with futures, then:

 import 'dart:async'; import 'package:stack_trace/stack_trace.dart'; main() async { print('Hello world: ${console_test.calculate()}!'); Chain.capture(() { return testFunction(); }, onError: (e, stackTrace) => print(Trace.format(new Chain.forTrace(stackTrace)))); } Future testFunction() async { throw new Exception("TEST"); } 

I get a more expected result:

 Hello world: 42! main.dart 17:3 testFunction.<async> dart:async _Completer.completeError main.dart 4:1 testFunction.<async> dart:async Future.Future main.dart 4:1 testFunction main.dart 11:26 main.<async>.<fn> package:stack_trace Chain.capture main.dart 10:16 main.<async> 

Am I doing something wrong? Is the chain incompatible with all asynchronous / pending?

+1
source share
2 answers

What versions of Dart and stack_trace are you using? On Dart 1.9.0-edge.44028 with stack_trace 1.2.3 , after deleting the console_test line, I get the following output:

 test.dart 16:3 testFunction.<async> dart:async _Completer.completeError test.dart 17:2 testFunction.<async> dart:async Future.Future.microtask test.dart 7:25 main.<async>.<fn>.<async> package:stack_trace Chain.capture test.dart 5:16 main.<async> 

It's also worth noting that you do not need to use Trace.format with Chain . You can simply use Chain.terse , which will also save asynchronous gaps.

+3
source

@ nex3 correctly pointed out that my original example actually works in version 1.9.0 dev for Dart, so this might be incompatible at the moment. Regardless of disabling the asynchronous Chain.capture, changing the wait on testFunction () to return and using the wait on Chain.Capture, actually produce the correct output. This is obviously not 100% optimal, but it does its job.

 main() async { print('Hello world: ${console_test.calculate()}!'); var test = await Chain.capture(() { return testFunction(); }, onError: (e, stackTrace) => print(Trace.format(new Chain.forTrace(stackTrace)))); print(test); } Future testFunction() async { return "nice!"; throw new Exception("TEST"); } 
0
source

Source: https://habr.com/ru/post/1215241/


All Articles