Stack traces
suggest changeA stack trace is the list of function calls that were active when an exception was thrown: the function that threw, the function that called it, its caller, and so on up to main. It answers the question an error message alone can't: where did this go wrong, and how did the program get there?
In Dart a stack trace is an object of type StackTrace. This article covers:
- getting the trace of a caught exception with
catch (e, st) - reading the frames of a trace
- capturing the current stack with
StackTrace.current - keeping the original trace:
rethrowversusthrow e - wrapping exceptions with
Error.throwWithStackTrace Error.stackTraceand why exceptions don't have one- passing traces through futures, completers and streams
- uncaught errors in zones and isolates
- parsing and formatting traces with
package:stack_trace - serializing traces and
StackTrace.fromString - traces in AOT-compiled executables, including decoding stripped traces
- stack overflow traces and the cost of capturing traces
The examples were run with Dart 3.13 on Windows. In the traces, the long absolute path of the project has been shortened to file:///C:/app. Each example was a separate file in bin/, which is why traces mention s1.dart, s2.dart and so on.
For the basics of throwing and catching see Exceptions; for a debugging-oriented introduction to traces, including Chain.capture for timers and callbacks, see Debugging.
Getting the trace of a caught exception
catch takes an optional second parameter. When you add it, Dart binds it to the stack trace of the exception:
int parseAge(String s) {
final age = int.parse(s);
if (age < 0) throw RangeError.value(age, 'age', 'must not be negative');
return age;
}
int averageAge(List<String> ages) {
var sum = 0;
for (final a in ages) {
sum += parseAge(a);
}
return sum ~/ ages.length;
}
void main() {
try {
averageAge(['31', '-4']);
} catch (e, st) {
print('error: $e');
print('type of st: ${st.runtimeType}');
print(st);
}
}
Output:
error: RangeError (age): must not be negative: -4
type of st: _StackTrace
#0 parseAge (file:///C:/app/bin/s1.dart:3:16)
#1 averageAge (file:///C:/app/bin/s1.dart:10:12)
#2 main (file:///C:/app/bin/s1.dart:17:5)
#3 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#4 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
The name st is just a convention (s, stack and stackTrace are common too). With on Type catch (e, st) it works the same way. The static type of the parameter is StackTrace; the runtime class is a private VM class you never need to name.
The StackTrace interface is tiny: essentially just toString(). All the information is in the text, which is why tools that analyze traces have to parse it (see the section on package:stack_trace below).
Reading a trace
Each line is one frame:
#1 averageAge (file:///C:/app/bin/s1.dart:10:12)
#1is the frame index.#0is where the exception was thrown,#1is the caller of#0, and so on. The last frames are the outermost calls.averageAgeis the function. Methods and getters show asClass.method, setters asClass.name=, constructors asnew Classornew Class.named, and closures asenclosing.<anonymous closure>.file:///C:/app/bin/s1.dart:10:12is the source location: file URI, line, column. Code from packages showspackage:name/file.dart, SDK code showsdart:core,dart:asyncand similar, ordart:core-patch/...for VM-specific internals.
Read the trace from the top and look for the first frame in your own code. Here #0 is already ours: parseAge threw at line 3, column 16, which is the RangeError.value expression. Line 10 of averageAge called it, and line 17 of main called averageAge. The last two frames are the VM starting main and are present in every trace.
Uncaught exceptions
If an exception escapes main, the VM prints Unhandled exception:, the error and its trace to stderr, and exits with code 255:
void validate(Map<String, Object?> user) {
if (user['email'] == null) {
throw ArgumentError('email is required');
}
}
void main() {
print('validating');
validate({'name': 'Ann'});
print('done');
}
Output (exit code 255):
validating
Unhandled exception:
Invalid argument(s): email is required
#0 validate (file:///C:/app/bin/s1b.dart:3:5)
#1 main (file:///C:/app/bin/s1b.dart:9:3)
#2 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#3 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
StackTrace.current
You don't need an exception to get a trace. StackTrace.current captures the stack at the point where it's evaluated:
String caller() {
// Frame 0 is caller() itself, frame 1 is whoever called it.
final lines = StackTrace.current.toString().split('\n');
return lines[1].replaceFirst(RegExp(r'^#\d+\s+'), '');
}
void saveUser() {
print('saveUser called from: ${caller()}');
}
void main() {
saveUser();
print(StackTrace.current);
}
Output:
saveUser called from: saveUser (file:///C:/app/bin/s2.dart:8:34)
#0 main (file:///C:/app/bin/s2.dart:13:20)
#1 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#2 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
Frame #0 of StackTrace.current is the function that evaluates it, so in caller() frame #1 is the function that called caller(). Note that the location in that frame points at the call site inside saveUser (line 8, column 34), not at the start of saveUser.
Typical uses are debug helpers, "who called this?" diagnostics, and attaching a trace to a log message that has no exception. Don't base program logic on it: the frame format is an implementation detail and differs between the VM, AOT executables and the web compilers, and inlining can remove frames in optimized code.
rethrow keeps the trace, throw e replaces it
When you catch an exception only to log it or clean up, use rethrow. It throws the same object with the original stack trace. throw e throws the same object too, but Dart records a new trace starting at the throw:
void readConfig() {
throw const FormatException('unexpected token at line 3');
}
void withRethrow() {
try {
readConfig();
} catch (e) {
print('withRethrow: logging and rethrowing');
rethrow;
}
}
void withThrow() {
try {
readConfig();
} catch (e) {
print('withThrow: logging and throwing again');
throw e;
}
}
void main() {
for (final f in [withRethrow, withThrow]) {
try {
f();
} catch (e, st) {
print(st.toString().split('\n').first);
}
}
}
Output:
withRethrow: logging and rethrowing
#0 readConfig (file:///C:/app/bin/s3.dart:2:3)
withThrow: logging and throwing again
#0 withThrow (file:///C:/app/bin/s3.dart:19:5)
After throw e the trace points at the catch block in withThrow and the real origin, readConfig, is gone. The linter rule use_rethrow_when_possible flags this mistake.
Wrapping exceptions without losing the trace
Often you want to translate a low-level exception into one that makes sense at a higher level, for example a FormatException into a ConfigException. A newly thrown object gets a new trace, so the original location is lost unless you keep it. There are two ways:
- Store the cause and its trace in the new exception.
- Throw the new exception with the old trace using
Error.throwWithStackTrace(error, stackTrace).
class ConfigException implements Exception {
final String message;
final Object cause;
final StackTrace causeStackTrace;
ConfigException(this.message, this.cause, this.causeStackTrace);
@override
String toString() => 'ConfigException: $message (caused by ${cause.runtimeType})';
}
int readPort(String raw) {
try {
return int.parse(raw);
} on FormatException catch (e, st) {
// Option 1: a new exception that carries the cause and its trace.
throw ConfigException('invalid port "$raw"', e, st);
}
}
int readTimeout(String raw) {
try {
return int.parse(raw);
} on FormatException catch (e, st) {
// Option 2: a new error object, but the original stack trace.
Error.throwWithStackTrace(
ConfigException('invalid timeout "$raw"', e, st), st);
}
}
void main() {
try {
readPort('80a');
} on ConfigException catch (e, st) {
print(e);
print('-- trace of the ConfigException:');
print(st.toString().split('\n').take(2).join('\n'));
print('-- trace of the cause:');
print(e.causeStackTrace.toString().split('\n')[4]);
}
try {
readTimeout('5s');
} on ConfigException catch (e, st) {
print(e);
print('-- trace of the ConfigException:');
print(st.toString().split('\n').take(5).join('\n'));
}
}
Output:
ConfigException: invalid port "80a" (caused by FormatException)
-- trace of the ConfigException:
#0 readPort (file:///C:/app/bin/s4.dart:17:5)
#1 main (file:///C:/app/bin/s4.dart:33:5)
-- trace of the cause:
#4 readPort (file:///C:/app/bin/s4.dart:14:16)
ConfigException: invalid timeout "5s" (caused by FormatException)
-- trace of the ConfigException:
#0 int._handleFormatError (dart:core-patch/integers_patch.dart:150:5)
#1 int._parseRadix (dart:core-patch/integers_patch.dart:179:14)
#2 int._parse (dart:core-patch/integers_patch.dart:121:12)
#3 int.parse (dart:core-patch/integers_patch.dart:81:12)
#4 readTimeout (file:///C:/app/bin/s4.dart:23:16)
With option 1 the ConfigException has its own trace (it was thrown at line 17) and you can still dig out the cause's trace. With option 2 the ConfigException reports the trace of the original int.parse failure directly, so anything that only looks at catch (e, st) (a logger, a crash reporter, the VM's unhandled exception handler) sees where the problem really started.
Error.throwWithStackTrace has return type Never, so the analyzer knows readTimeout doesn't need a return after it. Storing the cause, as in option 1, is still a good idea when you also want the cause's message. See Custom exception for designing exception classes.
Error.stackTrace
Dart separates Error (programming bugs: StateError, ArgumentError, RangeError...) from Exception (expected failures you should handle). One practical difference: an Error object remembers the trace of its first throw in its stackTrace property. Exceptions have no such field:
class NotFound implements Exception {
final String path;
NotFound(this.path);
@override
String toString() => 'NotFound: $path';
}
void main() {
// An Error records the trace of its first throw in .stackTrace.
try {
throw StateError('closed');
} catch (e) {
final err = e as Error;
print('Error.stackTrace: ${err.stackTrace.toString().split('\n').first}');
}
// Before it's thrown, an Error has no trace.
final unthrown = ArgumentError('x');
print('not thrown yet: ${unthrown.stackTrace}');
// Exceptions don't record anything; you only get the trace from catch.
try {
throw NotFound('/etc/app.conf');
} catch (e, st) {
print('$e has no stackTrace field; catch gave us: '
'${st.toString().split('\n').first}');
}
}
Output:
Error.stackTrace: #0 main (file:///C:/app/bin/s5.dart:11:5)
not thrown yet: null
NotFound: /etc/app.conf has no stackTrace field; catch gave us: #0 main (file:///C:/app/bin/s5.dart:23:5)
Error.stackTrace is set by the VM when the error is thrown the first time and never changes afterwards. That's handy when an error is passed around as a value: you can still find out where it was originally thrown. For exceptions, the only source of a trace is the second catch parameter, so pass it along explicitly.
Stack traces in async code
A Future or a Stream carries an error together with a stack trace. If you produce errors manually, you're responsible for supplying the trace.
import 'dart:async';
Future<int> withoutTrace() {
// No stack trace given, and the error was never thrown.
return Future.error(StateError('no trace given'));
}
Future<int> withTrace() {
try {
return Future.value(int.parse('x'));
} catch (e, st) {
return Future.error(e, st);
}
}
Future<String> lookup(String key) {
final completer = Completer<String>();
Timer(Duration.zero, () {
try {
if (key.isEmpty) throw ArgumentError('empty key');
completer.complete('value of $key');
} catch (e, st) {
completer.completeError(e, st);
}
});
return completer.future;
}
Stream<int> numbers() {
final controller = StreamController<int>();
controller.add(1);
try {
throw const FormatException('bad record');
} catch (e, st) {
controller.addError(e, st);
}
controller.close();
return controller.stream;
}
String top(StackTrace st) => st.toString().split('\n').first;
Future<void> main() async {
try {
await withoutTrace();
} catch (e, st) {
print('withoutTrace: ${top(st)}');
}
try {
await withTrace();
} catch (e, st) {
print('withTrace: ${top(st)}');
}
try {
await lookup('');
} catch (e, st) {
print('lookup: ${top(st)}');
}
await for (final n in numbers().handleError((Object e, StackTrace st) {
print('stream: ${top(st)}');
})) {
print('stream value: $n');
}
}
Output:
withoutTrace:
withTrace: #0 int._handleFormatError (dart:core-patch/integers_patch.dart:150:5)
lookup: #0 lookup.<anonymous closure> (file:///C:/app/bin/s6.dart:20:24)
stream value: 1
stream: #0 numbers (file:///C:/app/bin/s6.dart:33:5)
The pattern is the same everywhere: catch with (e, st) and pass both on.
Future.error(error, [stackTrace])Completer.completeError(error, [stackTrace])StreamController.addError(error, [stackTrace])andEventSink.addErrorFuture.catchError,Stream.handleErrorandonErrorcallbacks receive the trace when you declare a secondStackTraceparameter
When you leave the trace out, Dart uses the error's Error.stackTrace if it's an Error that was thrown before, and StackTrace.empty otherwise. That's why withoutTrace printed nothing:
Future<void> main() async {
try {
await Future<int>.error(StateError('never thrown'));
} catch (e, st) {
print('StackTrace.empty: ${identical(st, StackTrace.empty)}');
print('text: "$st"');
}
final err = ArgumentError('thrown once');
try {
throw err;
} catch (_) {}
try {
await Future<int>.error(err);
} catch (e, st) {
print('uses err.stackTrace: ${st.toString().split('\n').first}');
}
}
Output:
StackTrace.empty: true
text: ""
uses err.stackTrace: #0 main (file:///C:/app/bin/s6a.dart:11:5)
An empty trace in a log usually means some code created an error with Future.error(e) or completeError(e) and dropped the trace. Throwing inside an async function doesn't have this problem: throw records the trace and the async machinery passes it on.
await chains and asynchronous gaps
For code that uses await, the VM reconstructs the chain of awaiting functions and marks each suspension point with <asynchronous suspension>. Code in callbacks (Timer, Future.then, stream listeners) only shows the event loop that ran the callback, not who registered it. Debugging shows both cases side by side, and how Chain.capture from package:stack_trace fills the gaps while you debug.
Uncaught async errors and zones
A failed future that nobody awaits, or an exception thrown in a timer callback, never reaches a try/catch. By default the VM prints it as an unhandled exception and exits. runZonedGuarded lets you see such errors, with their traces, in one place:
import 'dart:async';
Future<void> sendReport() async {
await Future<void>.delayed(const Duration(milliseconds: 5));
throw StateError('report server unreachable');
}
void main() {
runZonedGuarded(() {
print('starting');
sendReport(); // no await, no catchError: nobody handles the failure
Timer(Duration.zero, () => throw const FormatException('bad timer data'));
}, (Object error, StackTrace st) {
print('uncaught: $error');
print(st);
});
}
Output:
starting
uncaught: FormatException: bad timer data
#0 main.<anonymous closure>.<anonymous closure> (file:///C:/app/bin/s7.dart:12:32)
#1 _rootRun (dart:async/zone_root.dart:27:47)
#2 _CustomZone.run (dart:async/zone.dart:810:35)
#3 _CustomZone.runGuarded (dart:async/zone.dart:702:7)
#4 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:743:23)
#5 _rootRun (dart:async/zone_root.dart:35:13)
#6 _CustomZone.run (dart:async/zone.dart:810:35)
#7 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:726:23)
#8 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
#9 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:423:19)
#10 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:454:5)
#11 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
uncaught: Bad state: report server unreachable
#0 sendReport (file:///C:/app/bin/s7.dart:5:3)
<asynchronous suspension>
In a zone, callbacks are wrapped by zone code, so traces from callbacks get several dart:async/zone frames. Your frame is still #0. In a real program the error handler would send the error and trace to a logger or crash reporting service; see "Catching uncaught errors" in Logging.
Isolates
Errors thrown in another isolate travel back with their traces. Isolate.run rethrows the error in the calling isolate with the remote stack trace:
import 'dart:isolate';
int heavyWork(int n) {
if (n > 10) throw ArgumentError.value(n, 'n', 'too big');
return n * n;
}
Future<void> main() async {
try {
await Isolate.run(() => heavyWork(42));
} catch (e, st) {
print('caught ${e.runtimeType}: $e');
print('trace type: ${st.runtimeType}');
print(st);
}
}
Output:
caught ArgumentError: Invalid argument (n): too big: 42
trace type: _StackTrace
#0 heavyWork (file:///C:/app/bin/s10.dart:4:15)
#1 main.<anonymous closure> (file:///C:/app/bin/s10.dart:10:29)
#2 _RemoteRunner._run (dart:isolate:1234:47)
#3 _RemoteRunner._remoteExecute (dart:isolate:1228:12)
#4 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:316:17)
#5 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
The trace shows the frames of the worker isolate, where heavyWork actually ran. If the error object can't be sent between isolates, Isolate.run throws a RemoteError instead, whose toString is the original error's text and whose stackTrace is the remote trace. With Isolate.spawn you get errors through onError as a two-element list [errorString, stackTraceString]; turn the second one into a StackTrace with StackTrace.fromString. See Isolates.
Parsing traces with package:stack_trace
Since a StackTrace is only text, use package:stack_trace when you need structured access to the frames:
dart pub add stack_trace
Trace.from(st) parses a trace from the VM (and also from browsers and other formats) into a list of Frame objects:
import 'package:stack_trace/stack_trace.dart';
int parseQuantity(String s) => int.parse(s);
void main() {
try {
parseQuantity('two');
} catch (e, st) {
final trace = Trace.from(st);
for (final f in trace.frames) {
print('${f.member} | ${f.library} | ${f.line}:${f.column}'
' | core: ${f.isCore}');
}
print('--- terse:');
print(trace.terse);
final mine = trace.frames.firstWhere((f) => !f.isCore && f.package == null);
print('--- first frame in my code: ${mine.member} at ${mine.location}');
}
}
Output:
int._handleFormatError | dart:core-patch/integers_patch.dart | 150:5 | core: true
int._parseRadix | dart:core-patch/integers_patch.dart | 179:14 | core: true
int._parse | dart:core-patch/integers_patch.dart | 121:12 | core: true
int.parse | dart:core-patch/integers_patch.dart | 81:12 | core: true
parseQuantity | bin\s8.dart | 3:36 | core: false
main | bin\s8.dart | 7:5 | core: false
_delayEntrypointInvocation.<fn> | dart:isolate-patch/isolate_patch.dart | 313:19 | core: true
_RawReceivePort._handleMessage | dart:isolate-patch/isolate_patch.dart | 192:12 | core: true
--- terse:
dart:core int.parse
bin\s8.dart 3:36 parseQuantity
bin\s8.dart 7:5 main
--- first frame in my code: parseQuantity at bin\s8.dart 3:36
Useful Frame members:
| Member | Meaning |
|---|---|
member |
function name, with closures shortened to <fn> |
uri |
full Uri of the source file |
library |
uri shortened: relative to the current directory, package: or dart: |
line, column |
position, null if unknown |
location |
library plus line:column, ready to print |
package |
package name for package: URIs, otherwise null |
isCore |
true for dart: frames |
trace.terse folds consecutive SDK frames into one, drops the VM's startup frames and prints one aligned line per frame. That's the format package:test uses for failing tests. library uses the platform's path separator, which is why the output above has bin\s8.dart on Windows; on Linux and macOS it would be bin/s8.dart.
Trace.current([level]) is the parsed equivalent of StackTrace.current, and its level argument skips frames. This makes a "who called me" helper reliable and easy to read:
import 'package:stack_trace/stack_trace.dart';
void audit(String action) {
// Trace.current(1) skips audit itself; frames.first is the caller.
final caller = Trace.current(1).frames.first;
print('$action from ${caller.member} at ${caller.location}');
}
class Account {
void withdraw(int cents) => audit('withdraw $cents');
}
void main() {
Account().withdraw(500);
audit('startup');
}
Output:
withdraw 500 from Account.withdraw at bin\s9.dart 10:31
startup from main at bin\s9.dart 15:3
The package also has Chain for asynchronous chains, Trace.format(st) to format a raw trace tersely in one call, and foldFrames to collapse frames of libraries you're not interested in.
A compact trace for log lines
Without any package, a few lines of code can turn a trace into a one-line summary for logs. It keeps only frames from your own files and shortens their paths:
/// Formats [st] for a log line: drops SDK frames and shortens file URIs.
String compactTrace(StackTrace st, {int maxFrames = 5}) {
final frame = RegExp(r'^#\d+\s+(.+) \((.+)\)$');
final out = <String>[];
for (final line in st.toString().split('\n')) {
final m = frame.firstMatch(line);
if (m == null) continue; // blank lines, <asynchronous suspension>
final location = m.group(2)!;
if (location.startsWith('dart:')) continue;
final short = location.startsWith('file:')
? location.substring(location.lastIndexOf('/') + 1)
: location;
out.add('${m.group(1)} @ $short');
if (out.length == maxFrames) break;
}
return out.join(' <- ');
}
Future<Map<String, Object?>> loadOrder(String id) async {
await Future<void>.delayed(Duration.zero);
final qty = int.parse(id.split('-').last);
return {'id': id, 'qty': qty};
}
Future<void> main() async {
try {
await loadOrder('order-x');
} catch (e, st) {
print('ERROR ${e.runtimeType}: ${compactTrace(st)}');
}
}
Output:
ERROR FormatException: loadOrder @ s14.dart:21:19 <- main @ s14.dart:27:5
This relies on the VM's frame format #N member (location), so it's fine for logging, but use package:stack_trace if the code also has to handle traces from the web or AOT builds.
Sending traces elsewhere: StackTrace.fromString
Traces often need to leave the process: to a log file, a crash reporting service or another isolate. Convert them with toString(), and turn the text back into a StackTrace with StackTrace.fromString:
import 'dart:convert';
// What a client might send to an error-reporting endpoint.
String encodeReport(Object error, StackTrace st) =>
jsonEncode({'error': error.toString(), 'stack': st.toString()});
void main() {
String json;
try {
throw UnsupportedError('export to PDF');
} catch (e, st) {
json = encodeReport(e, st);
}
// ...later, on the receiving side:
final map = jsonDecode(json) as Map<String, dynamic>;
final st = StackTrace.fromString(map['stack'] as String);
print(map['error']);
print(st.toString().split('\n').first);
// A StackTrace can also be used to rethrow with the remote trace.
try {
Error.throwWithStackTrace(StateError(map['error'] as String), st);
} catch (e, st2) {
print('rethrown with remote trace: ${identical(st, st2)}');
}
}
Output:
Unsupported operation: export to PDF
#0 main (file:///C:/app/bin/s11.dart:10:5)
rethrown with remote trace: true
StackTrace.fromString doesn't parse anything; it wraps the string so it can be passed wherever a StackTrace is expected, such as Error.throwWithStackTrace, Future.error or a logger. Its toString() returns the original text.
StackTrace.empty is the counterpart for "no trace available". Pass it explicitly when an API requires a trace and you truly have none, rather than inventing one with StackTrace.current, which would point at the wrong place.
Traces in compiled executables
Programs compiled with dart compile exe (AOT) still print symbolic traces, but without column numbers:
$ dart compile exe bin/s1b.dart -o out/s1b.exe
$ out/s1b.exe
validating
Unhandled exception:
Invalid argument(s): email is required
#0 validate (file:///C:/app/bin/s1b.dart:3)
#1 main (file:///C:/app/bin/s1b.dart:9)
#2 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313)
#3 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192)
AOT code is heavily optimized, so expect inlined functions to disappear from traces now and then.
To make the executable smaller, strip the debugging information into a separate file with -S (--save-debugging-info). The traces then contain only addresses:
$ dart compile exe bin/s1b.dart -o out/s1s.exe -S out/s1s.debug
$ out/s1s.exe 2> out/crash.txt
validating
$ cat out/crash.txt
Unhandled exception:
Invalid argument(s): email is required
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 1868, tid: 25644, name Dart_Initialize
os: windows arch: x64 comp: no sim: no
build_id: 'ede53b7817577874bfe61af37a50a527'
isolate_dso_base: 262453d0000, vm_dso_base: 0
isolate_instructions: 26245404000, vm_instructions: 0
#00 abs 0000026245439b8a virt 0000000000069b8a _kDartSnapshotText+0x35b8a
#01 abs 0000026245439aed virt 0000000000069aed _kDartSnapshotText+0x35aed
#02 abs 0000026245439dc2 virt 0000000000069dc2 _kDartSnapshotText+0x35dc2
#03 abs 00000262454441e6 virt 00000000000741e6 _kDartSnapshotText+0x401e6
#04 abs 000002624543a206 virt 000000000006a206 _kDartSnapshotText+0x36206
#05 abs 0000026245443ae4 virt 0000000000073ae4 _kDartSnapshotText+0x3fae4
#06 abs 000002624543bac8 virt 000000000006bac8 _kDartSnapshotText+0x37ac8
Keep the .debug file of every release build (the build_id identifies which one belongs to a crash). The decode tool from package:native_stack_traces translates such a trace back into a symbolic one, this time even with columns:
$ dart pub add --dev native_stack_traces
$ dart run native_stack_traces:decode translate -d out/s1s.debug -i out/crash.txt
Unhandled exception:
Invalid argument(s): email is required
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
pid: 1868, tid: 25644, name Dart_Initialize
os: windows arch: x64 comp: no sim: no
build_id: 'ede53b7817577874bfe61af37a50a527'
isolate_dso_base: 262453d0000, vm_dso_base: 0
isolate_instructions: 26245404000, vm_instructions: 0
#0 validate (file:///C:/app/bin/s1b.dart:3:5)
#1 main (file:///C:/app/bin/s1b.dart:9:3)
#2 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:313:19)
#3 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
Flutter's --split-debug-info produces the same kind of file and is decoded the same way (flutter symbolize wraps it). For more on building executables see Compiling to executables.
Stack overflow traces
Infinite recursion ends with a StackOverflowError. Its trace would have tens of thousands of frames, so the VM keeps the innermost and outermost frames and replaces the middle with ...:
int depth(int n) => depth(n + 1) + 1;
void main() {
try {
depth(0);
} on StackOverflowError catch (e, st) {
final lines = st.toString().trim().split('\n');
print('$e: ${lines.length} lines');
print(lines.take(2).join('\n'));
print(lines.sublist(42, 47).join('\n'));
print(lines.last);
}
}
Output:
Stack Overflow: 88 lines
#0 depth (file:///C:/app/bin/s12.dart:1:1)
#1 depth (file:///C:/app/bin/s12.dart:1:21)
#42 depth (file:///C:/app/bin/s12.dart:1:21)
#43 depth (file:///C:/app/bin/s12.dart:1:21)
...
...
#18988 depth (file:///C:/app/bin/s12.dart:1:21)
#19029 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
The frame numbers after the gap (about 19,000 here) tell you how deep the recursion went. The repeating frame at the top is the recursive call; look for the missing or wrong base case there. The Recursion article shows how to convert deep recursion into a loop.
The cost of capturing traces
Capturing a trace walks the stack, and formatting it as a string is several times more expensive:
void main() {
const n = 100000;
var sw = Stopwatch()..start();
var count = 0;
for (var i = 0; i < n; i++) {
count += StackTrace.current.hashCode & 1;
}
final capture = sw.elapsedMicroseconds / n;
sw = Stopwatch()..start();
for (var i = 0; i < n; i++) {
count += StackTrace.current.toString().length & 1;
}
final format = sw.elapsedMicroseconds / n;
print('StackTrace.current: ${capture.toStringAsFixed(2)} us');
print('StackTrace.current.toString(): ${format.toStringAsFixed(2)} us');
if (count < 0) print(count);
}
Output:
StackTrace.current: 0.90 us
StackTrace.current.toString(): 6.64 us
These numbers are from a shallow stack; deeper stacks cost more. A microsecond is nothing when handling an error, but it adds up if you capture a trace for every log message or every object you create. That's why package:logging only records traces automatically when you set recordStackTraceAtLevel, and why Chain.capture is meant for debugging only.
Every throw captures a trace too, which is one reason not to use exceptions for normal control flow in hot loops.
Summary
- Use
catch (e, st)to get the stack trace of a caught exception; it's aStackTracewhose only real content is itstoString(). - Read traces from the top and find the first frame in your own code;
#0is where the exception was thrown. StackTrace.currentcaptures the current stack; frame#0is the function evaluating it.- Use
rethrow, notthrow e, to rethrow with the original trace. - When wrapping an exception, keep the original trace with
Error.throwWithStackTraceand/or store the cause and its trace in the new exception. - Thrown
Errorobjects remember their trace instackTrace; exceptions don't. - Always pass the trace to
Future.error,Completer.completeErrorandaddError; otherwise you getStackTrace.empty. - Use
runZonedGuardedto catch uncaught async errors with their traces;Isolate.runbrings back the remote trace. package:stack_traceparses traces into frames (Trace.from,Trace.current,terse) and chains async gaps.StackTrace.fromStringturns stored or transmitted text back into aStackTrace.- AOT executables print traces without columns; with
-Sthey print addresses thatnative_stack_traces:decodetranslates using the saved debug file.