期货/承诺,追踪错误

mse*_*don 2 future promise dart dart-async

简而言之,简单的代码片段,Futures(dart)或Promises(js)似乎为回调的恐怖提供了一个模糊有用的解决方案.

使用大型软件时会出现问题,例如,您正在与之交谈的服务器开始返回垃圾邮件,从而触发一个深埋在第三方代码中的迄今未见过的异常​​.此时,在一个令人难以置信的长链.then的某个地方,以catchError结束,你将成为新的"空指针异常"之类的幸运接收者.它从哪里来的?谁知道?显然,我们并没有使用这些技术神奇地获取调用堆栈,并且没有任何使用的跟踪信息 - 在这个巨大的链中可能会调用50次特定函数,并且在某些任意调用时会引发错误.

面对这种情况时,最好采用哪些策略?

Set*_*add 6

即将推出的名为Zones的功能应该会有所帮助.另外,退房getAttachedStackTrace.

此示例打印"catchError内部":

import 'dart:async';

void main() {
  runZonedExperimental(() {
    new Future.value(1)
      .then((v) => v)
      .then((v) => throw new ArgumentError('testing'))
      .then((v) => v)
      .catchError((e) => print('inside of catchError'));
  },
  onError: print);
}
Run Code Online (Sandbox Code Playgroud)

此示例打印'in onError':

import 'dart:async';

void main() {
  runZonedExperimental(() {
    new Future.value(1)
      .then((v) => v)
      .then((v) => throw new ArgumentError('testing'))
      .then((v) => v);
  },
  onError: (e) => print('in onError'));
}
Run Code Online (Sandbox Code Playgroud)

此示例打印"in onError:Illegal argument(s):testing":

import 'dart:async';

void main() {
  runZonedExperimental(() {
    new Future.value(1)
      .then((v) => v)
      .then((v) => throw new ArgumentError('testing'))
      .then((v) => v);
  },
  onError: (e) => print('in onError: $e'));
}
Run Code Online (Sandbox Code Playgroud)

此示例打印出堆栈跟踪,其中包含发生原始异常的文件和行号:

#0      main.<anonymous closure>.<anonymous closure> (file:///Users/sethladd/dart/zoneexperiment/bin/zoneexperiment.dart:7:20)
Run Code Online (Sandbox Code Playgroud)

代码:

import 'dart:async';

void main() {
  runZonedExperimental(() {
    new Future.value(1)
      .then((v) => v)
      .then((v) => throw new ArgumentError('testing'))
      .then((v) => v);
  },
  onError: (e) => print(getAttachedStackTrace(e)));
}
Run Code Online (Sandbox Code Playgroud)

区域应该在1.0之前移出实验区域.

getAttachedStackTrace的文档:http://api.dartlang.org/docs/releases/latest/dart_async.html#getAttachedStackTrace

runZoned的文档:http://api.dartlang.org/docs/releases/latest/dart_async.html#runZonedExperimental