在Dart中断言失败时如何打印消息?

时间:2015-08-24 17:29:20

标签: dart

我们想在assert()失败时打印一条消息。目前在Dart中,断言只接受布尔值。我们希望向开发人员提供明确的理由和说明,以便在断言失败时做什么。

3 个答案:

答案 0 :(得分:9)

Dart 1.22开始,assert()会收到一条可选消息。

assert(configFile != null, "Tool config missing.");

如果断言失败,它将产生如下内容:

Unhandled exception:
'file:///.../main.dart': Failed assertion: line 9 pos 10:
'configFile != null': Tool config missing.
#0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:33)
#1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:29)
#2      main (file:///.../main.dart:9:10)

请注意,错误消息包含实际断言(configFile != null)。

答案 1 :(得分:4)

解决方法https://github.com/dart-lang/sdk/issues/6190#issuecomment-119103626

存在一个未解决的问题
assert(() => test || throw "message");

我试过这个,但这样做并不起作用。略微修改的工作版本

var test = false;
assert(test ? true : throw "message");

另见

答案 2 :(得分:2)

如果要通过命令行执行dart文件,只需添加以下内容即可启用断言,请参见参考文献here

dart --enable-asserts main.dart
相关问题