wrapMain function
A wrapper for the body of the top-level main()
method.
It's recommended that all scripts wrap their main()
methods in this
function. It gracefully exits when an error is unhandled, and (if
chainStackTraces
is true
) tracks stack traces across asynchronous calls
to produce better error stacks.
By default, if a Script fails in callback
, this just exits with that
script's exit code without printing any additional error messages. If
printScriptException
is true
(or if it's unset and debug
is true
),
this will print the exception and its stack trace to stderr before exiting.
By default, stack frames from the Dart core libraries and from this package
will be folded together to make stack traces more readable. If
verboseTrace
is true
, the full stack traces will be printed instead.
If debug
is true
, extra information about Scripts' lifecycles will be
printed directly to stderr. As the name suggests, this is intended for use
only when debugging.
Implementation
void wrapMain(FutureOr<void> callback(),
{bool chainStackTraces = true,
bool? printScriptException,
bool verboseTrace = false,
bool debug = false}) {
withConfig(() {
Chain.capture(callback, onError: (error, chain) {
if (error is! ScriptException) {
stderr.writeln(error);
stderr.writeln(terseChain(chain));
// Use the same exit code that Dart does for unhandled exceptions.
exit(254);
}
if (printScriptException ?? debug) {
stderr.writeln(error);
stderr.writeln(terseChain(chain));
}
exit(error.exitCode);
}, when: chainStackTraces);
}, verboseTrace: verboseTrace, debug: debug);
}