在Dart中,如何在断言失败时打印消息?
我们希望在在Dart中,如何在断言失败时打印消息?,dart,Dart,我们希望在assert()失败时打印消息。目前在Dart中,断言只接受布尔值。我们希望为开发人员提供明确的原因和说明,说明在断言失败时该怎么做。解决方法存在一个悬而未决的问题 我试过了,但这样不行。略加修改的工作版本 var test = false; assert(test ? true : throw "message"); 另见 自开始,assert()接受可选消息 assert(configFile != null, "Tool config missing."); 如果断言
assert()
失败时打印消息。目前在Dart中,断言只接受布尔值。我们希望为开发人员提供明确的原因和说明,说明在断言失败时该怎么做。解决方法存在一个悬而未决的问题
我试过了,但这样不行。略加修改的工作版本
var test = false;
assert(test ? true : throw "message");
另见
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
)。如果您通过命令行执行dart文件,则需要按如下方式启用断言,请参阅参考:
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)
dart --enable-asserts main.dart