traceback function

List<List<Span>> traceback(
  1. Object error,
  2. StackTrace stack, {
  3. bool allFrames = false,
  4. int context = 2,
  5. ThemeData? theme,
  6. Style? errorStyle,
  7. Style? hintStyle,
  8. SourceLines? sourceLines,
})

error thrown at stack as lines of spans, for a program to write where it ends on it: what was thrown, the source of the app's own code it was thrown in, and the frames that led there.

✗ StateError: Bad state: the config has no "name"

  lib/src/config.dart:42:7
    40 │   final map = jsonDecode(text) as Map<String, Object?>;
    41 │   if (map['name'] == null) {
  ▶ 42 │     throw StateError('the config has no "name"');
    43 │   }

  lib/src/config.dart:42:7  Config.load
  … 3 frames of dart:async
  bin/tool.dart:12:3        main
  • The first line is the error's type and its toString(), the type left out where the text starts with it (FormatException: …) or the error is a string; the lines after it, where the text has more, are indented under it. All of it in errorStyle, the theme's ThemeData.error without, red without either.
  • Then the lines around the one the stack names first in the app's own code (RecordFrame.isAppCode: neither the SDK, nor twk and its packages, nor the pub cache), context on each side of it, under its place (SourceExcerpt), the code as sourceLines gives it, the text of the lines without. Left out where there is no such frame, or its file can't be read (an AOT build, the source changed or gone).
  • Then the frames, a line each, the location and the member: the runs of frames not of the app's own code between the app's folded into a line saying how many and whose (stackLines), unless allFrames.

The places, the line numbers and the folded frames are in hintStyle, the theme's ThemeData.muted without, and without either in the terminal's own colour dim, which reads on a dark background and a light one alike. sourceLines gets the theme, the terminal's own colours without one. The places are paths from the working directory where they are in it, each a link to its file. The VM keeps no local variables to show.

try {
  load();
} on Object catch (error, stack) {
  for (final line in traceback(error, stack)) {
    print(line.map((span) => span.text).join());
  }
}

Implementation

List<List<Span>> traceback(
  Object error,
  StackTrace stack, {
  bool allFrames = false,
  int context = 2,
  ThemeData? theme,
  Style? errorStyle,
  Style? hintStyle,
  SourceLines? sourceLines,
}) {
  final glyphs = theme?.glyphs ?? Glyphs.unicode;
  final style = errorStyle ?? theme?.error ?? const Style(fg: Color.red);
  final hint =
      hintStyle ??
      theme?.muted ??
      const Style(fg: Color.defaultColor, attrs: Attr.dim);
  final text = _describe(error).split('\n');
  final lines = <List<Span>>[
    [Span('${glyphs.cross} ', style), Span(text.first, style.merge(_bold))],
    for (final line in text.skip(1))
      [if (line.isNotEmpty) Span('  $line', style)],
  ];

  final frames = stackLines(stack, fold: false);
  final app = frames
      .map((line) => line.frame)
      .firstWhere(
        (f) => f != null && f.isAppCode && f.path != null && f.line != null,
        orElse: () => null,
      );
  final excerpt = app == null
      ? null
      : SourceExcerpt.read(
          app.path!,
          app.line!,
          column: app.column,
          context: context,
        );
  if (excerpt != null) {
    lines
      ..add(const [])
      ..addAll(
        _excerptLines(
          excerpt,
          (sourceLines ?? _plain)(
            excerpt,
            theme ?? const ThemeData.terminal(Brightness.dark),
          ),
          style,
          hint,
          glyphs,
        ),
      );
  }

  final shown = allFrames ? frames : stackLines(stack);
  if (shown.isNotEmpty) {
    var width = 0;
    for (final line in shown) {
      final location = line.frame?.location.length ?? 0;
      if (location <= _locationColumn && location > width) {
        width = location;
      }
    }
    lines.add(const []);
    for (final line in shown) {
      final frame = line.frame;
      lines.add(
        frame == null
            ? [Span('  ${line.text}', hint)]
            : [
                const Span('  '),
                Span(frame.location, _linked(hint, frame.path)),
                Span(
                  '${' ' * (width - frame.location.length).clamp(0, width)}'
                  '  ${frame.member}',
                ),
              ],
      );
    }
  }
  return lines;
}