[英]How to print a message when an assert fails, in Dart?
We'd like to print a message when an assert()
fails. 我们想在assert()
失败时打印一条消息。 Currently in Dart, an assert only takes a boolean. 目前在Dart中,断言只接受布尔值。 We'd like to give the developer explicit reasons and instructions for what to do when the assert fails. 我们想给开发人员明确的理由和说明,以便在断言失败时做什么。
As of Dart 1.22 , assert()
takes an optional message. 从Dart 1.22开始 , assert()
接受一个可选的消息。
assert(configFile != null, "Tool config missing.");
If the assertion fails, it will produce something like the following: 如果断言失败,它将产生如下内容:
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)
Note that the error message includes the actual assertion ( configFile != null
). 请注意,错误消息包括实际断言( configFile != null
)。
只是要补充一点,如果你是通过命令行执行一个dart文件,你需要按如下方式启用断言,参见这里的参考:
dart --enable-asserts main.dart
There is an open issue with a workaround https://github.com/dart-lang/sdk/issues/6190#issuecomment-119103626 解决方法有一个未解决的问题https://github.com/dart-lang/sdk/issues/6190#issuecomment-119103626
assert(() => test || throw "message");
I tried this but this way it doesn't work. 我试过这个,但这样做不起作用。 A slightly modified working version 略微修改的工作版本
var test = false;
assert(test ? true : throw "message");
See also 也可以看看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.