assertions.dart 50.1 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
import 'package:meta/meta.dart';

7
import 'basic_types.dart';
8
import 'constants.dart';
9
import 'diagnostics.dart';
10
import 'print.dart';
11
import 'stack_frame.dart';
12

13
// Examples can assume:
14 15 16 17
// late String runtimeType;
// late bool draconisAlive;
// late bool draconisAmulet;
// late Diagnosticable draconis;
18
// void methodThatMayThrow() { }
19

20
/// Signature for [FlutterError.onError] handler.
21
typedef FlutterExceptionHandler = void Function(FlutterErrorDetails details);
22

23 24 25
/// Signature for [DiagnosticPropertiesBuilder] transformer.
typedef DiagnosticPropertiesTransformer = Iterable<DiagnosticsNode> Function(Iterable<DiagnosticsNode> properties);

26
/// Signature for [FlutterErrorDetails.informationCollector] callback
27 28 29
/// and other callbacks that collect information describing an error.
typedef InformationCollector = Iterable<DiagnosticsNode> Function();

30 31 32 33 34 35 36 37
/// Signature for a function that demangles [StackTrace] objects into a format
/// that can be parsed by [StackFrame].
///
/// See also:
///
///   * [FlutterError.demangleStackTrace], which shows an example implementation.
typedef StackTraceDemangler = StackTrace Function(StackTrace details);

38 39 40 41 42 43 44 45 46 47
/// Partial information from a stack frame for stack filtering purposes.
///
/// See also:
///
///  * [RepetitiveStackFrameFilter], which uses this class to compare against [StackFrame]s.
@immutable
class PartialStackFrame {
  /// Creates a new [PartialStackFrame] instance. All arguments are required and
  /// must not be null.
  const PartialStackFrame({
48 49 50
    required this.package,
    required this.className,
    required this.method,
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  }) : assert(className != null),
       assert(method != null),
       assert(package != null);

  /// An `<asynchronous suspension>` line in a stack trace.
  static const PartialStackFrame asynchronousSuspension = PartialStackFrame(
    package: '',
    className: '',
    method: 'asynchronous suspension',
  );

  /// The package to match, e.g. `package:flutter/src/foundation/assertions.dart`,
  /// or `dart:ui/window.dart`.
  final Pattern package;

  /// The class name for the method.
  ///
  /// On web, this is ignored, since class names are not available.
  ///
  /// On all platforms, top level methods should use the empty string.
  final String className;

  /// The method name for this frame line.
  ///
  /// On web, private methods are wrapped with `[]`.
  final String method;

  /// Tests whether the [StackFrame] matches the information in this
  /// [PartialStackFrame].
  bool matches(StackFrame stackFrame) {
    final String stackFramePackage = '${stackFrame.packageScheme}:${stackFrame.package}/${stackFrame.packagePath}';
    // Ideally this wouldn't be necessary.
    // TODO(dnfield): https://github.com/dart-lang/sdk/issues/40117
    if (kIsWeb) {
      return package.allMatches(stackFramePackage).isNotEmpty
          && stackFrame.method == (method.startsWith('_') ? '[$method]' : method);
    }
    return package.allMatches(stackFramePackage).isNotEmpty
        && stackFrame.method == method
        && stackFrame.className == className;
  }
}

/// A class that filters stack frames for additional filtering on
/// [FlutterError.defaultStackFilter].
abstract class StackFilter {
97 98
  /// Abstract const constructor. This constructor enables subclasses to provide
  /// const constructors so that they can be used in const expressions.
99 100
  const StackFilter();

101
  /// Filters the list of [StackFrame]s by updating corresponding indices in
102 103
  /// `reasons`.
  ///
104
  /// To elide a frame or number of frames, set the string.
105
  void filter(List<StackFrame> stackFrames, List<String?> reasons);
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
}


/// A [StackFilter] that filters based on repeating lists of
/// [PartialStackFrame]s.
///
/// See also:
///
///   * [FlutterError.addDefaultStackFilter], a method to register additional
///     stack filters for [FlutterError.defaultStackFilter].
///   * [StackFrame], a class that can help with parsing stack frames.
///   * [PartialStackFrame], a class that helps match partial method information
///     to a stack frame.
class RepetitiveStackFrameFilter extends StackFilter {
  /// Creates a new RepetitiveStackFrameFilter. All parameters are required and must not be
  /// null.
  const RepetitiveStackFrameFilter({
123 124
    required this.frames,
    required this.replacement,
125 126 127
  }) : assert(frames != null),
       assert(replacement != null);

128
  /// The shape of this repetitive stack pattern.
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  final List<PartialStackFrame> frames;

  /// The number of frames in this pattern.
  int get numFrames => frames.length;

  /// The string to replace the frames with.
  ///
  /// If the same replacement string is used multiple times in a row, the
  /// [FlutterError.defaultStackFilter] will simply update a counter after this
  /// line rather than repeating it.
  final String replacement;

  List<String> get _replacements => List<String>.filled(numFrames, replacement);

  @override
144
  void filter(List<StackFrame> stackFrames, List<String?> reasons) {
145
    for (int index = 0; index < stackFrames.length - numFrames; index += 1) {
146 147 148 149 150 151 152 153
      if (_matchesFrames(stackFrames.skip(index).take(numFrames).toList())) {
        reasons.setRange(index, index + numFrames, _replacements);
        index += numFrames - 1;
      }
    }
  }

  bool _matchesFrames(List<StackFrame> stackFrames) {
154 155 156
    if (stackFrames.length < numFrames) {
      return false;
    }
157 158 159 160 161 162 163 164 165
    for (int index = 0; index < stackFrames.length; index++) {
      if (!frames[index].matches(stackFrames[index])) {
        return false;
      }
    }
    return true;
  }
}

166 167 168 169 170 171
abstract class _ErrorDiagnostic extends DiagnosticsProperty<List<Object>> {
  /// This constructor provides a reliable hook for a kernel transformer to find
  /// error messages that need to be rewritten to include object references for
  /// interactive display of errors.
  _ErrorDiagnostic(
    String message, {
172 173 174 175 176 177 178 179 180 181 182 183
    DiagnosticsTreeStyle style = DiagnosticsTreeStyle.flat,
    DiagnosticLevel level = DiagnosticLevel.info,
  }) : assert(message != null),
       super(
         null,
         <Object>[message],
         showName: false,
         showSeparator: false,
         defaultValue: null,
         style: style,
         level: level,
       );
184 185

  /// In debug builds, a kernel transformer rewrites calls to the default
186
  /// constructors for [ErrorSummary], [ErrorDescription], and [ErrorHint] to use
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  /// this constructor.
  //
  // ```dart
  // _ErrorDiagnostic('Element $element must be $color')
  // ```
  // Desugars to:
  // ```dart
  // _ErrorDiagnostic.fromParts(<Object>['Element ', element, ' must be ', color])
  // ```
  //
  // Slightly more complex case:
  // ```dart
  // _ErrorDiagnostic('Element ${element.runtimeType} must be $color')
  // ```
  // Desugars to:
  //```dart
  // _ErrorDiagnostic.fromParts(<Object>[
  //   'Element ',
  //   DiagnosticsProperty(null, element, description: element.runtimeType?.toString()),
  //   ' must be ',
  //   color,
  // ])
  // ```
  _ErrorDiagnostic._fromParts(
    List<Object> messageParts, {
    DiagnosticsTreeStyle style = DiagnosticsTreeStyle.flat,
    DiagnosticLevel level = DiagnosticLevel.info,
  }) : assert(messageParts != null),
       super(
         null,
         messageParts,
         showName: false,
         showSeparator: false,
         defaultValue: null,
         style: style,
         level: level,
       );

225 226 227 228

  @override
  List<Object> get value => super.value!;

229
  @override
230
  String valueToString({ TextTreeConfiguration? parentConfiguration }) {
231
    return value.join();
232 233 234 235 236 237 238 239 240
  }
}

/// An explanation of the problem and its cause, any information that may help
/// track down the problem, background information, etc.
///
/// Use [ErrorDescription] for any part of an error message where neither
/// [ErrorSummary] or [ErrorHint] is appropriate.
///
241 242 243 244
/// In debug builds, values interpolated into the `message` are
/// expanded and placed into [value], which is of type [List<Object>].
/// This allows IDEs to examine values interpolated into error messages.
///
245 246
/// See also:
///
247 248 249 250
///  * [ErrorSummary], which provides a short (one line) description of the
///    problem that was detected.
///  * [ErrorHint], which provides specific, non-obvious advice that may be
///    applicable.
251
///  * [ErrorSpacer], which renders as a blank line.
252 253
///  * [FlutterError], which is the most common place to use an
///    [ErrorDescription].
254 255 256 257 258 259 260 261 262 263
class ErrorDescription extends _ErrorDiagnostic {
  /// A lint enforces that this constructor can only be called with a string
  /// literal to match the limitations of the Dart Kernel transformer that
  /// optionally extracts out objects referenced using string interpolation in
  /// the message passed in.
  ///
  /// The message will display with the same text regardless of whether the
  /// kernel transformer is used. The kernel transformer is required so that
  /// debugging tools can provide interactive displays of objects described by
  /// the error.
264
  ErrorDescription(super.message) : super(level: DiagnosticLevel.info);
265 266 267

  /// Calls to the default constructor may be rewritten to use this constructor
  /// in debug mode using a kernel transformer.
268
  // ignore: unused_element
269
  ErrorDescription._fromParts(super.messageParts) : super._fromParts(level: DiagnosticLevel.info);
270 271 272 273 274 275 276 277 278 279 280
}

/// A short (one line) description of the problem that was detected.
///
/// Error summaries from the same source location should have little variance,
/// so that they can be recognized as related. For example, they shouldn't
/// include hash codes.
///
/// A [FlutterError] must start with an [ErrorSummary] and may not contain
/// multiple summaries.
///
281 282 283 284
/// In debug builds, values interpolated into the `message` are
/// expanded and placed into [value], which is of type [List<Object>].
/// This allows IDEs to examine values interpolated into error messages.
///
285 286
/// See also:
///
287 288 289 290 291 292
///  * [ErrorDescription], which provides an explanation of the problem and its
///    cause, any information that may help track down the problem, background
///    information, etc.
///  * [ErrorHint], which provides specific, non-obvious advice that may be
///    applicable.
///  * [FlutterError], which is the most common place to use an [ErrorSummary].
293 294 295 296 297 298 299 300 301 302
class ErrorSummary extends _ErrorDiagnostic {
  /// A lint enforces that this constructor can only be called with a string
  /// literal to match the limitations of the Dart Kernel transformer that
  /// optionally extracts out objects referenced using string interpolation in
  /// the message passed in.
  ///
  /// The message will display with the same text regardless of whether the
  /// kernel transformer is used. The kernel transformer is required so that
  /// debugging tools can provide interactive displays of objects described by
  /// the error.
303
  ErrorSummary(super.message) : super(level: DiagnosticLevel.summary);
304 305 306

  /// Calls to the default constructor may be rewritten to use this constructor
  /// in debug mode using a kernel transformer.
307
  // ignore: unused_element
308
  ErrorSummary._fromParts(super.messageParts) : super._fromParts(level: DiagnosticLevel.summary);
309 310 311 312
}

/// An [ErrorHint] provides specific, non-obvious advice that may be applicable.
///
313
/// If your message provides obvious advice that is always applicable, it is an
314 315
/// [ErrorDescription] not a hint.
///
316 317 318 319
/// In debug builds, values interpolated into the `message` are
/// expanded and placed into [value], which is of type [List<Object>].
/// This allows IDEs to examine values interpolated into error messages.
///
320 321
/// See also:
///
322 323 324 325 326
///  * [ErrorSummary], which provides a short (one line) description of the
///    problem that was detected.
///  * [ErrorDescription], which provides an explanation of the problem and its
///    cause, any information that may help track down the problem, background
///    information, etc.
327
///  * [ErrorSpacer], which renders as a blank line.
328
///  * [FlutterError], which is the most common place to use an [ErrorHint].
329 330 331 332 333 334 335 336 337 338
class ErrorHint extends _ErrorDiagnostic {
  /// A lint enforces that this constructor can only be called with a string
  /// literal to match the limitations of the Dart Kernel transformer that
  /// optionally extracts out objects referenced using string interpolation in
  /// the message passed in.
  ///
  /// The message will display with the same text regardless of whether the
  /// kernel transformer is used. The kernel transformer is required so that
  /// debugging tools can provide interactive displays of objects described by
  /// the error.
339
  ErrorHint(super.message) : super(level:DiagnosticLevel.hint);
340 341 342

  /// Calls to the default constructor may be rewritten to use this constructor
  /// in debug mode using a kernel transformer.
343
  // ignore: unused_element
344
  ErrorHint._fromParts(super.messageParts) : super._fromParts(level:DiagnosticLevel.hint);
345
}
346

347 348 349
/// An [ErrorSpacer] creates an empty [DiagnosticsNode], that can be used to
/// tune the spacing between other [DiagnosticsNode] objects.
class ErrorSpacer extends DiagnosticsProperty<void> {
Dan Field's avatar
Dan Field committed
350
  /// Creates an empty space to insert into a list of [DiagnosticsNode] objects
351 352 353 354 355 356 357 358 359
  /// typically within a [FlutterError] object.
  ErrorSpacer() : super(
    '',
    null,
    description: '',
    showName: false,
  );
}

360 361
/// Class for information provided to [FlutterExceptionHandler] callbacks.
///
362
/// {@tool snippet}
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
/// This is an example of using [FlutterErrorDetails] when calling
/// [FlutterError.reportError].
///
/// ```dart
/// void main() {
///   try {
///     // Try to do something!
///   } catch (error) {
///     // Catch & report error.
///     FlutterError.reportError(FlutterErrorDetails(
///       exception: error,
///       library: 'Flutter test framework',
///       context: ErrorSummary('while running async test code'),
///     ));
///   }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
///   * [FlutterError.onError], which is called whenever the Flutter framework
385
///     catches an error.
386
class FlutterErrorDetails with Diagnosticable {
387 388 389 390 391
  /// Creates a [FlutterErrorDetails] object with the given arguments setting
  /// the object's properties.
  ///
  /// The framework calls this constructor when catching an exception that will
  /// subsequently be reported using [FlutterError.onError].
392 393 394 395
  ///
  /// The [exception] must not be null; other arguments can be left to
  /// their default values. (`throw null` results in a
  /// [NullThrownError] exception.)
396
  const FlutterErrorDetails({
397
    required this.exception,
398
    this.stack,
399
    this.library = 'Flutter framework',
400
    this.context,
401
    this.stackFilter,
402
    this.informationCollector,
403
    this.silent = false,
404
  }) : assert(exception != null);
405

406 407 408
  /// Creates a copy of the error details but with the given fields replaced
  /// with new values.
  FlutterErrorDetails copyWith({
409
    DiagnosticsNode? context,
410
    Object? exception,
411 412 413 414 415
    InformationCollector? informationCollector,
    String? library,
    bool? silent,
    StackTrace? stack,
    IterableFilter<String>? stackFilter,
416 417 418 419 420 421 422 423 424 425 426 427
  }) {
    return FlutterErrorDetails(
      context: context ?? this.context,
      exception: exception ?? this.exception,
      informationCollector: informationCollector ?? this.informationCollector,
      library: library ?? this.library,
      silent: silent ?? this.silent,
      stack: stack ?? this.stack,
      stackFilter: stackFilter ?? this.stackFilter,
    );
  }

428 429 430 431 432 433 434 435 436 437 438 439 440 441
  /// Transformers to transform [DiagnosticsNode] in [DiagnosticPropertiesBuilder]
  /// into a more descriptive form.
  ///
  /// There are layers that attach certain [DiagnosticsNode] into
  /// [FlutterErrorDetails] that require knowledge from other layers to parse.
  /// To correctly interpret those [DiagnosticsNode], register transformers in
  /// the layers that possess the knowledge.
  ///
  /// See also:
  ///
  ///  * [WidgetsBinding.initInstances], which registers its transformer.
  static final List<DiagnosticPropertiesTransformer> propertiesTransformers =
    <DiagnosticPropertiesTransformer>[];

442 443
  /// The exception. Often this will be an [AssertionError], maybe specifically
  /// a [FlutterError]. However, this could be any value at all.
444
  final Object exception;
445 446 447 448

  /// The stack trace from where the [exception] was thrown (as opposed to where
  /// it was caught).
  ///
449 450 451
  /// StackTrace objects are opaque except for their [toString] function.
  ///
  /// If this field is not null, then the [stackFilter] callback, if any, will
452
  /// be called with the result of calling [toString] on this object and
453 454 455 456
  /// splitting that result on line breaks. If there's no [stackFilter]
  /// callback, then [FlutterError.defaultStackFilter] is used instead. That
  /// function expects the stack to be in the format used by
  /// [StackTrace.toString].
457
  final StackTrace? stack;
458 459 460 461

  /// A human-readable brief name describing the library that caught the error
  /// message. This is used by the default error handler in the header dumped to
  /// the console.
462
  final String? library;
463

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
  /// A [DiagnosticsNode] that provides a human-readable description of where
  /// the error was caught (as opposed to where it was thrown).
  ///
  /// The node, e.g. an [ErrorDescription], should be in a form that will make
  /// sense in English when following the word "thrown", as in "thrown while
  /// obtaining the image from the network" (for the context "while obtaining
  /// the image from the network").
  ///
  /// {@tool snippet}
  /// This is an example of using and [ErrorDescription] as the
  /// [FlutterErrorDetails.context] when calling [FlutterError.reportError].
  ///
  /// ```dart
  /// void maybeDoSomething() {
  ///   try {
  ///     // Try to do something!
  ///   } catch (error) {
  ///     // Catch & report error.
  ///     FlutterError.reportError(FlutterErrorDetails(
  ///       exception: error,
  ///       library: 'Flutter test framework',
  ///       context: ErrorDescription('while dispatching notifications for $runtimeType'),
  ///     ));
  ///   }
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// See also:
493
  ///
494 495 496 497 498 499 500 501 502
  ///  * [ErrorDescription], which provides an explanation of the problem and
  ///    its cause, any information that may help track down the problem,
  ///    background information, etc.
  ///  * [ErrorSummary], which provides a short (one line) description of the
  ///    problem that was detected.
  ///  * [ErrorHint], which provides specific, non-obvious advice that may be
  ///    applicable.
  ///  * [FlutterError], which is the most common place to use
  ///    [FlutterErrorDetails].
503
  final DiagnosticsNode? context;
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518
  /// A callback which filters the [stack] trace. Receives an iterable of
  /// strings representing the frames encoded in the way that
  /// [StackTrace.toString()] provides. Should return an iterable of lines to
  /// output for the stack.
  ///
  /// If this is not provided, then [FlutterError.dumpErrorToConsole] will use
  /// [FlutterError.defaultStackFilter] instead.
  ///
  /// If the [FlutterError.defaultStackFilter] behavior is desired, then the
  /// callback should manually call that function. That function expects the
  /// incoming list to be in the [StackTrace.toString()] format. The output of
  /// that function, however, does not always follow this format.
  ///
  /// This won't be called if [stack] is null.
519
  final IterableFilter<String>? stackFilter;
520

521 522
  /// A callback which will provide information that could help with debugging
  /// the problem.
523
  ///
524 525 526
  /// Information collector callbacks can be expensive, so the generated
  /// information should be cached by the caller, rather than the callback being
  /// called multiple times.
527
  ///
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
  /// The callback is expected to return an iterable of [DiagnosticsNode] objects,
  /// typically implemented using `sync*` and `yield`.
  ///
  /// {@tool snippet}
  /// In this example, the information collector returns two pieces of information,
  /// one broadly-applicable statement regarding how the error happened, and one
  /// giving a specific piece of information that may be useful in some cases but
  /// may also be irrelevant most of the time (an argument to the method).
  ///
  /// ```dart
  /// void climbElevator(int pid) {
  ///   try {
  ///     // ...
  ///   } catch (error, stack) {
  ///     FlutterError.reportError(FlutterErrorDetails(
  ///       exception: error,
  ///       stack: stack,
545 546 547 548
  ///       informationCollector: () => <DiagnosticsNode>[
  ///         ErrorDescription('This happened while climbing the space elevator.'),
  ///         ErrorHint('The process ID is: $pid'),
  ///       ],
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  ///     ));
  ///   }
  /// }
  /// ```
  /// {@end-tool}
  ///
  /// The following classes may be of particular use:
  ///
  ///  * [ErrorDescription], for information that is broadly applicable to the
  ///    situation being described.
  ///  * [ErrorHint], for specific information that may not always be applicable
  ///    but can be helpful in certain situations.
  ///  * [DiagnosticsStackTrace], for reporting stack traces.
  ///  * [ErrorSpacer], for adding spaces (a blank line) between other items.
  ///
  /// For objects that implement [Diagnosticable] one may consider providing
  /// additional information by yielding the output of the object's
  /// [Diagnosticable.toDiagnosticsNode] method.
567
  final InformationCollector? informationCollector;
568 569 570 571 572 573 574 575

  /// Whether this error should be ignored by the default error reporting
  /// behavior in release mode.
  ///
  /// If this is false, the default, then the default error handler will always
  /// dump this error to the console.
  ///
  /// If this is true, then the default error handler would only dump this error
576
  /// to the console in debug mode. In release mode, the error is ignored.
577 578 579 580 581 582 583
  ///
  /// This is used by certain exception handlers that catch errors that could be
  /// triggered by environmental conditions (as opposed to logic errors). For
  /// example, the HTTP library sets this flag so as to not report every 404
  /// error to the console on end-user devices, while still allowing a custom
  /// error handler to see the errors even in release builds.
  final bool silent;
584 585 586

  /// Converts the [exception] to a string.
  ///
587 588 589
  /// This applies some additional logic to make [AssertionError] exceptions
  /// prettier, to handle exceptions that stringify to empty strings, to handle
  /// objects that don't inherit from [Exception] or [Error], and so forth.
590
  String exceptionAsString() {
591
    String? longMessage;
592 593 594 595
    if (exception is AssertionError) {
      // Regular _AssertionErrors thrown by assert() put the message last, after
      // some code snippets. This leads to ugly messages. To avoid this, we move
      // the assertion message up to before the code snippets, separated by a
596
      // newline, if we recognize that format is being used.
597
      final Object? message = (exception as AssertionError).message;
598 599 600 601 602 603 604
      final String fullMessage = exception.toString();
      if (message is String && message != fullMessage) {
        if (fullMessage.length > message.length) {
          final int position = fullMessage.lastIndexOf(message);
          if (position == fullMessage.length - message.length &&
              position > 2 &&
              fullMessage.substring(position - 2, position) == ': ') {
605 606 607 608 609 610 611 612
            // Add a linebreak so that the filename at the start of the
            // assertion message is always on its own line.
            String body = fullMessage.substring(0, position - 2);
            final int splitPoint = body.indexOf(' Failed assertion:');
            if (splitPoint >= 0) {
              body = '${body.substring(0, splitPoint)}\n${body.substring(splitPoint + 1)}';
            }
            longMessage = '${message.trimRight()}\n$body';
613 614 615 616 617
          }
        }
      }
      longMessage ??= fullMessage;
    } else if (exception is String) {
618
      longMessage = exception as String;
619 620 621
    } else if (exception is Error || exception is Exception) {
      longMessage = exception.toString();
    } else {
622
      longMessage = '  $exception';
623 624
    }
    longMessage = longMessage.trimRight();
625
    if (longMessage.isEmpty) {
626
      longMessage = '  <no message available>';
627
    }
628 629
    return longMessage;
  }
630

631
  Diagnosticable? _exceptionToDiagnosticable() {
632
    final Object exception = this.exception;
633
    if (exception is FlutterError) {
634
      return exception;
635 636
    }
    if (exception is AssertionError && exception.message is FlutterError) {
637
      return exception.message! as FlutterError;
638 639 640 641 642 643 644 645 646
    }
    return null;
  }

  /// Returns a short (one line) description of the problem that was detected.
  ///
  /// If the exception contains an [ErrorSummary] that summary is used,
  /// otherwise the summary is inferred from the string representation of the
  /// exception.
647 648 649
  ///
  /// In release mode, this always returns a [DiagnosticsNode.message] with a
  /// formatted version of the exception.
650
  DiagnosticsNode get summary {
651 652 653 654
    String formatException() => exceptionAsString().split('\n')[0].trimLeft();
    if (kReleaseMode) {
      return DiagnosticsNode.message(formatException());
    }
655 656
    final Diagnosticable? diagnosticable = _exceptionToDiagnosticable();
    DiagnosticsNode? summary;
657 658 659
    if (diagnosticable != null) {
      final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
      debugFillProperties(builder);
660
      summary = builder.properties.cast<DiagnosticsNode?>().firstWhere((DiagnosticsNode? node) => node!.level == DiagnosticLevel.summary, orElse: () => null);
661
    }
662
    return summary ?? ErrorSummary(formatException());
663 664
  }

665
  @override
666 667 668
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    final DiagnosticsNode verb = ErrorDescription('thrown${ context != null ? ErrorDescription(" $context") : ""}');
669
    final Diagnosticable? diagnosticable = _exceptionToDiagnosticable();
670 671 672 673 674
    if (exception is NullThrownError) {
      properties.add(ErrorDescription('The null value was $verb.'));
    } else if (exception is num) {
      properties.add(ErrorDescription('The number $exception was $verb.'));
    } else {
675
      final DiagnosticsNode errorName;
676 677 678 679 680 681
      if (exception is AssertionError) {
        errorName = ErrorDescription('assertion');
      } else if (exception is String) {
        errorName = ErrorDescription('message');
      } else if (exception is Error || exception is Exception) {
        errorName = ErrorDescription('${exception.runtimeType}');
682
      } else {
683
        errorName = ErrorDescription('${exception.runtimeType} object');
684
      }
685 686 687
      properties.add(ErrorDescription('The following $errorName was $verb:'));
      if (diagnosticable != null) {
        diagnosticable.debugFillProperties(properties);
688
      } else {
689 690 691 692 693
        // Many exception classes put their type at the head of their message.
        // This is redundant with the way we display exceptions, so attempt to
        // strip out that header when we see it.
        final String prefix = '${exception.runtimeType}: ';
        String message = exceptionAsString();
694
        if (message.startsWith(prefix)) {
695
          message = message.substring(prefix.length);
696
        }
697
        properties.add(ErrorSummary(message));
698 699 700
      }
    }

701 702 703 704 705 706 707 708
    if (stack != null) {
      if (exception is AssertionError && diagnosticable == null) {
        // After popping off any dart: stack frames, are there at least two more
        // stack frames coming from package flutter?
        //
        // If not: Error is in user code (user violated assertion in framework).
        // If so:  Error is in Framework. We either need an assertion higher up
        //         in the stack, or we've violated our own assertions.
709
        final List<StackFrame> stackFrames = StackFrame.fromStackTrace(FlutterError.demangleStackTrace(stack!))
710 711 712 713 714 715 716 717 718 719 720 721
                                                       .skipWhile((StackFrame frame) => frame.packageScheme == 'dart')
                                                       .toList();
        final bool ourFault =  stackFrames.length >= 2
                            && stackFrames[0].package == 'flutter'
                            && stackFrames[1].package == 'flutter';
        if (ourFault) {
          properties.add(ErrorSpacer());
          properties.add(ErrorHint(
            'Either the assertion indicates an error in the framework itself, or we should '
            'provide substantially more information in this error message to help you determine '
            'and fix the underlying cause.\n'
            'In either case, please report this assertion by filing a bug on GitHub:\n'
722
            '  https://github.com/flutter/flutter/issues/new?template=2_bug.md',
723
          ));
724 725
        }
      }
726
      properties.add(ErrorSpacer());
727
      properties.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', stack, stackFilter: stackFilter));
728 729
    }
    if (informationCollector != null) {
730
      properties.add(ErrorSpacer());
731
      informationCollector!().forEach(properties.add);
732 733 734 735 736
    }
  }

  @override
  String toStringShort() {
737
    return library != null ? 'Exception caught by $library' : 'Exception caught';
738 739 740
  }

  @override
741
  String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
742
    return toDiagnosticsNode(style: DiagnosticsTreeStyle.error).toStringDeep(minLevel: minLevel);
743
  }
744 745

  @override
746
  DiagnosticsNode toDiagnosticsNode({ String? name, DiagnosticsTreeStyle? style }) {
747 748 749 750 751 752
    return _FlutterErrorDetailsNode(
      name: name,
      value: this,
      style: style,
    );
  }
753 754
}

755 756
/// Error class used to report Flutter-specific assertion failures and
/// contract violations.
757 758 759 760 761
///
/// See also:
///
///  * <https://flutter.dev/docs/testing/errors>, more information about error
///    handling in Flutter.
762 763
class FlutterError extends Error with DiagnosticableTreeMixin implements AssertionError {
  /// Create an error message from a string.
764
  ///
765 766 767 768 769 770
  /// The message may have newlines in it. The first line should be a terse
  /// description of the error, e.g. "Incorrect GlobalKey usage" or "setState()
  /// or markNeedsBuild() called during build". Subsequent lines should contain
  /// substantial additional information, ideally sufficient to develop a
  /// correct solution to the problem.
  ///
771
  /// In some cases, when a [FlutterError] is reported to the user, only the first
772 773 774
  /// line is included. For example, Flutter will typically only fully report
  /// the first exception at runtime, displaying only the first line of
  /// subsequent errors.
775 776 777
  ///
  /// All sentences in the error should be correctly punctuated (i.e.,
  /// do end the error message with a period).
778
  ///
779
  /// This constructor defers to the [FlutterError.fromParts] constructor.
780 781
  /// The first line is wrapped in an implied [ErrorSummary], and subsequent
  /// lines are wrapped in implied [ErrorDescription]s. Consider using the
782
  /// [FlutterError.fromParts] constructor to provide more detail, e.g.
783 784 785
  /// using [ErrorHint]s or other [DiagnosticsNode]s.
  factory FlutterError(String message) {
    final List<String> lines = message.split('\n');
786 787 788 789
    return FlutterError.fromParts(<DiagnosticsNode>[
      ErrorSummary(lines.first),
      ...lines.skip(1).map<DiagnosticsNode>((String line) => ErrorDescription(line)),
    ]);
790
  }
791

792 793
  /// Create an error message from a list of [DiagnosticsNode]s.
  ///
Dan Field's avatar
Dan Field committed
794
  /// By convention, there should be exactly one [ErrorSummary] in the list,
795 796 797 798 799 800 801
  /// and it should be the first entry.
  ///
  /// Other entries are typically [ErrorDescription]s (for material that is
  /// always applicable for this error) and [ErrorHint]s (for material that may
  /// be sometimes useful, but may not always apply). Other [DiagnosticsNode]
  /// subclasses, such as [DiagnosticsStackTrace], may
  /// also be used.
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
  ///
  /// When using an [ErrorSummary], [ErrorDescription]s, and [ErrorHint]s, in
  /// debug builds, values interpolated into the `message` arguments of those
  /// classes' constructors are expanded and placed into the
  /// [DiagnosticsProperty.value] property of those objects (which is of type
  /// [List<Object>]). This allows IDEs to examine values interpolated into
  /// error messages.
  ///
  /// Alternatively, to include a specific [Diagnosticable] object into the
  /// error message and have the object describe itself in detail (see
  /// [DiagnosticsNode.toStringDeep]), consider calling
  /// [Diagnosticable.toDiagnosticsNode] on that object and using that as one of
  /// the values passed to this constructor.
  ///
  /// {@tool snippet}
  /// In this example, an error is thrown in debug mode if certain conditions
  /// are not met. The error message includes a description of an object that
  /// implements the [Diagnosticable] interface, `draconis`.
  ///
  /// ```dart
  /// void controlDraconis() {
  ///   assert(() {
  ///     if (!draconisAlive || !draconisAmulet) {
  ///       throw FlutterError.fromParts(<DiagnosticsNode>[
  ///         ErrorSummary('Cannot control Draconis in current state.'),
  ///         ErrorDescription('Draconis can only be controlled while alive and while the amulet is wielded.'),
  ///         if (!draconisAlive)
  ///           ErrorHint('Draconis is currently not alive.'),
  ///         if (!draconisAmulet)
  ///           ErrorHint('The Amulet of Draconis is currently not wielded.'),
  ///         draconis.toDiagnosticsNode(name: 'Draconis'),
  ///       ]);
  ///     }
  ///     return true;
  ///   }());
  ///   // ...
  /// }
  /// ```
  /// {@end-tool}
841 842 843 844 845 846 847
  FlutterError.fromParts(this.diagnostics) : assert(diagnostics.isNotEmpty, FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Empty FlutterError')])) {
    assert(
      diagnostics.first.level == DiagnosticLevel.summary,
      FlutterError.fromParts(<DiagnosticsNode>[
        ErrorSummary('FlutterError is missing a summary.'),
        ErrorDescription(
          'All FlutterError objects should start with a short (one line) '
848
          'summary description of the problem that was detected.',
849 850 851 852 853 854
        ),
        DiagnosticsProperty<FlutterError>('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace),
        ErrorDescription(
          '\nThis error should still help you solve your problem, '
          'however please also report this malformed error in the '
          'framework by filing a bug on GitHub:\n'
855
          '  https://github.com/flutter/flutter/issues/new?template=2_bug.md',
856
        ),
857 858
      ]),
    );
859 860 861 862 863 864 865 866
    assert(() {
      final Iterable<DiagnosticsNode> summaries = diagnostics.where((DiagnosticsNode node) => node.level == DiagnosticLevel.summary);
      if (summaries.length > 1) {
        final List<DiagnosticsNode> message = <DiagnosticsNode>[
          ErrorSummary('FlutterError contained multiple error summaries.'),
          ErrorDescription(
            'All FlutterError objects should have only a single short '
            '(one line) summary description of the problem that was '
867
            'detected.',
868
          ),
869 870
          DiagnosticsProperty<FlutterError>('Malformed', this, expandableValue: true, showSeparator: false, style: DiagnosticsTreeStyle.whitespace),
          ErrorDescription('\nThe malformed error has ${summaries.length} summaries.'),
871 872
        ];
        int i = 1;
873
        for (final DiagnosticsNode summary in summaries) {
874 875 876 877 878 879 880
          message.add(DiagnosticsProperty<DiagnosticsNode>('Summary $i', summary, expandableValue : true));
          i += 1;
        }
        message.add(ErrorDescription(
          '\nThis error should still help you solve your problem, '
          'however please also report this malformed error in the '
          'framework by filing a bug on GitHub:\n'
881
          '  https://github.com/flutter/flutter/issues/new?template=2_bug.md',
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
        ));
        throw FlutterError.fromParts(message);
      }
      return true;
    }());
  }

  /// The information associated with this error, in structured form.
  ///
  /// The first node is typically an [ErrorSummary] giving a short description
  /// of the problem, suitable for an index of errors, a log, etc.
  ///
  /// Subsequent nodes should give information specific to this error. Typically
  /// these will be [ErrorDescription]s or [ErrorHint]s, but they could be other
  /// objects also. For instance, an error relating to a timer could include a
  /// stack trace of when the timer was scheduled using the
  /// [DiagnosticsStackTrace] class.
  final List<DiagnosticsNode> diagnostics;

  /// The message associated with this error.
  ///
  /// This is generated by serializing the [diagnostics].
904
  @override
905
  String get message => toString();
906 907 908

  /// Called whenever the Flutter framework catches an error.
  ///
909
  /// The default behavior is to call [presentError].
910 911
  ///
  /// You can set this to your own function to override this default behavior.
912 913 914
  /// For example, you could report all errors to your server. Consider calling
  /// [presentError] from your custom error handler in order to see the logs in
  /// the console as well.
915 916 917
  ///
  /// If the error handler throws an exception, it will not be caught by the
  /// Flutter framework.
918 919 920
  ///
  /// Set this to null to silently catch and ignore errors. This is not
  /// recommended.
921 922 923
  ///
  /// Do not call [onError] directly, instead, call [reportError], which
  /// forwards to [onError] if it is not null.
924 925 926 927 928
  ///
  /// See also:
  ///
  ///  * <https://flutter.dev/docs/testing/errors>, more information about error
  ///    handling in Flutter.
929
  static FlutterExceptionHandler? onError = presentError;
930

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
  /// Called by the Flutter framework before attempting to parse a [StackTrace].
  ///
  /// Some [StackTrace] implementations have a different toString format from
  /// what the framework expects, like ones from package:stack_trace. To make
  /// sure we can still parse and filter mangled [StackTrace]s, the framework
  /// first calls this function to demangle them.
  ///
  /// This should be set in any environment that could propagate a non-standard
  /// stack trace to the framework. Otherwise, the default behavior is to assume
  /// all stack traces are in a standard format.
  ///
  /// The following example demangles package:stack_trace traces by converting
  /// them into vm traces, which the framework is able to parse:
  ///
  /// ```dart
  /// FlutterError.demangleStackTrace = (StackTrace stackTrace) {
  ///   if (stack is stack_trace.Trace)
948 949 950 951
  ///     return stack.vmTrace;
  ///   if (stack is stack_trace.Chain)
  ///     return stack.toTrace().vmTrace;
  ///   return stack;
952 953
  /// };
  /// ```
954 955 956
  static StackTraceDemangler demangleStackTrace = _defaultStackTraceDemangler;

  static StackTrace _defaultStackTraceDemangler(StackTrace stackTrace) => stackTrace;
957

958 959 960 961 962 963 964 965 966 967
  /// Called whenever the Flutter framework wants to present an error to the
  /// users.
  ///
  /// The default behavior is to call [dumpErrorToConsole].
  ///
  /// Plugins can override how an error is to be presented to the user. For
  /// example, the structured errors service extension sets its own method when
  /// the extension is enabled. If you want to change how Flutter responds to an
  /// error, use [onError] instead.
  static FlutterExceptionHandler presentError = dumpErrorToConsole;
968 969 970

  static int _errorCount = 0;

971 972 973 974 975 976 977 978
  /// Resets the count of errors used by [dumpErrorToConsole] to decide whether
  /// to show a complete error message or an abbreviated one.
  ///
  /// After this is called, the next error message will be shown in full.
  static void resetErrorCount() {
    _errorCount = 0;
  }

979 980 981 982 983
  /// The width to which [dumpErrorToConsole] will wrap lines.
  ///
  /// This can be used to ensure strings will not exceed the length at which
  /// they will wrap, e.g. when placing ASCII art diagrams in messages.
  static const int wrapWidth = 100;
984

985 986 987 988 989
  /// Prints the given exception details to the console.
  ///
  /// The first time this is called, it dumps a very verbose message to the
  /// console using [debugPrint].
  ///
990 991
  /// Subsequent calls only dump the first line of the exception, unless
  /// `forceReport` is set to true (in which case it dumps the verbose message).
992
  ///
993 994 995
  /// Call [resetErrorCount] to cause this method to go back to acting as if it
  /// had not been called before (so the next message is verbose again).
  ///
996
  /// The default behavior for the [onError] handler is to call this function.
997
  static void dumpErrorToConsole(FlutterErrorDetails details, { bool forceReport = false }) {
998 999
    assert(details != null);
    assert(details.exception != null);
1000
    bool isInDebugMode = false;
1001
    assert(() {
1002
      // In debug mode, we ignore the "silent" flag.
1003
      isInDebugMode = true;
1004
      return true;
1005
    }());
1006
    final bool reportError = isInDebugMode || details.silent != true; // could be null
1007
    if (!reportError && !forceReport) {
1008
      return;
1009
    }
1010
    if (_errorCount == 0 || forceReport) {
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
      // Diagnostics is only available in debug mode. In profile and release modes fallback to plain print.
      if (isInDebugMode) {
        debugPrint(
          TextTreeRenderer(
            wrapWidthProperties: wrapWidth,
            maxDescendentsTruncatableNode: 5,
          ).render(details.toDiagnosticsNode(style: DiagnosticsTreeStyle.error)).trimRight(),
        );
      } else {
        debugPrintStack(
          stackTrace: details.stack,
          label: details.exception.toString(),
          maxFrames: 100,
        );
      }
1026
    } else {
1027
      debugPrint('Another exception was thrown: ${details.summary}');
1028 1029 1030 1031
    }
    _errorCount += 1;
  }

1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
  static final List<StackFilter> _stackFilters = <StackFilter>[];

  /// Adds a stack filtering function to [defaultStackFilter].
  ///
  /// For example, the framework adds common patterns of element building to
  /// elide tree-walking patterns in the stacktrace.
  ///
  /// Added filters are checked in order of addition. The first matching filter
  /// wins, and subsequent filters will not be checked.
  static void addDefaultStackFilter(StackFilter filter) {
    _stackFilters.add(filter);
  }

1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
  /// Converts a stack to a string that is more readable by omitting stack
  /// frames that correspond to Dart internals.
  ///
  /// This is the default filter used by [dumpErrorToConsole] if the
  /// [FlutterErrorDetails] object has no [FlutterErrorDetails.stackFilter]
  /// callback.
  ///
  /// This function expects its input to be in the format used by
  /// [StackTrace.toString()]. The output of this function is similar to that
  /// format but the frame numbers will not be consecutive (frames are elided)
  /// and the final line may be prose rather than a stack frame.
  static Iterable<String> defaultStackFilter(Iterable<String> frames) {
1057 1058 1059 1060 1061 1062 1063 1064 1065
    final Map<String, int> removedPackagesAndClasses = <String, int>{
      'dart:async-patch': 0,
      'dart:async': 0,
      'package:stack_trace': 0,
      'class _AssertionError': 0,
      'class _FakeAsync': 0,
      'class _FrameCallbackEntry': 0,
      'class _Timer': 0,
      'class _RawReceivePortImpl': 0,
1066
    };
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
    int skipped = 0;

    final List<StackFrame> parsedFrames = StackFrame.fromStackString(frames.join('\n'));

    for (int index = 0; index < parsedFrames.length; index += 1) {
      final StackFrame frame = parsedFrames[index];
      final String className = 'class ${frame.className}';
      final String package = '${frame.packageScheme}:${frame.package}';
      if (removedPackagesAndClasses.containsKey(className)) {
        skipped += 1;
1077
        removedPackagesAndClasses.update(className, (int value) => value + 1);
1078 1079 1080 1081
        parsedFrames.removeAt(index);
        index -= 1;
      } else if (removedPackagesAndClasses.containsKey(package)) {
        skipped += 1;
1082
        removedPackagesAndClasses.update(package, (int value) => value + 1);
1083 1084 1085 1086
        parsedFrames.removeAt(index);
        index -= 1;
      }
    }
1087
    final List<String?> reasons = List<String?>.filled(parsedFrames.length, null);
1088 1089 1090 1091
    for (final StackFilter filter in _stackFilters) {
      filter.filter(parsedFrames, reasons);
    }

1092
    final List<String> result = <String>[];
1093 1094 1095 1096 1097 1098

    // Collapse duplicated reasons.
    for (int index = 0; index < parsedFrames.length; index += 1) {
      final int start = index;
      while (index < reasons.length - 1 && reasons[index] != null && reasons[index + 1] == reasons[index]) {
        index++;
Dan Field's avatar
Dan Field committed
1099
      }
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
      String suffix = '';
      if (reasons[index] != null) {
        if (index != start) {
          suffix = ' (${index - start + 2} frames)';
        } else {
          suffix = ' (1 frame)';
        }
      }
      final String resultLine = '${reasons[index] ?? parsedFrames[index].source}$suffix';
      result.add(resultLine);
1110
    }
1111 1112 1113 1114 1115

    // Only include packages we actually elided from.
    final List<String> where = <String>[
      for (MapEntry<String, int> entry in removedPackagesAndClasses.entries)
        if (entry.value > 0)
1116
          entry.key,
1117 1118 1119 1120
    ]..sort();
    if (skipped == 1) {
      result.add('(elided one frame from ${where.single})');
    } else if (skipped > 1) {
1121
      if (where.length > 1) {
1122
        where[where.length - 1] = 'and ${where.last}';
1123
      }
1124
      if (where.length > 2) {
1125
        result.add('(elided $skipped frames from ${where.join(", ")})');
1126
      } else {
1127
        result.add('(elided $skipped frames from ${where.join(" ")})');
1128 1129 1130 1131 1132
      }
    }
    return result;
  }

1133 1134
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
1135
    diagnostics.forEach(properties.add);
1136 1137 1138 1139 1140 1141
  }

  @override
  String toStringShort() => 'FlutterError';

  @override
1142
  String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
1143 1144 1145 1146
    if (kReleaseMode) {
      final Iterable<_ErrorDiagnostic> errors = diagnostics.whereType<_ErrorDiagnostic>();
      return errors.isNotEmpty ? errors.first.valueToString() : toStringShort();
    }
1147 1148 1149 1150 1151
    // Avoid wrapping lines.
    final TextTreeRenderer renderer = TextTreeRenderer(wrapWidth: 4000000000);
    return diagnostics.map((DiagnosticsNode node) => renderer.render(node).trimRight()).join('\n');
  }

1152
  /// Calls [onError] with the given details, unless it is null.
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
  ///
  /// {@tool snippet}
  /// When calling this from a `catch` block consider annotating the method
  /// containing the `catch` block with
  /// `@pragma('vm:notify-debugger-on-exception')` to allow an attached debugger
  /// to treat the exception as unhandled. This means instead of executing the
  /// `catch` block, the debugger can break at the original source location from
  /// which the exception was thrown.
  ///
  /// ```dart
  /// @pragma('vm:notify-debugger-on-exception')
  /// void doSomething() {
  ///   try {
  ///     methodThatMayThrow();
  ///   } catch (exception, stack) {
  ///     FlutterError.reportError(FlutterErrorDetails(
  ///       exception: exception,
  ///       stack: stack,
  ///       library: 'example library',
  ///       context: ErrorDescription('while doing something'),
  ///     ));
  ///   }
  /// }
  /// ```
  /// {@end-tool}
1178 1179 1180
  static void reportError(FlutterErrorDetails details) {
    assert(details != null);
    assert(details.exception != null);
1181
    onError?.call(details);
1182
  }
1183
}
1184

1185
/// Dump the stack to the console using [debugPrint] and
1186 1187
/// [FlutterError.defaultStackFilter].
///
1188 1189
/// If the `stackTrace` parameter is null, the [StackTrace.current] is used to
/// obtain the stack.
1190 1191
///
/// The `maxFrames` argument can be given to limit the stack to the given number
1192 1193
/// of lines before filtering is applied. By default, all stack lines are
/// included.
1194 1195
///
/// The `label` argument, if present, will be printed before the stack.
1196
void debugPrintStack({StackTrace? stackTrace, String? label, int? maxFrames}) {
1197
  if (label != null) {
1198
    debugPrint(label);
1199
  }
1200 1201 1202 1203 1204
  if (stackTrace == null) {
    stackTrace = StackTrace.current;
  } else {
    stackTrace = FlutterError.demangleStackTrace(stackTrace);
  }
1205
  Iterable<String> lines = stackTrace.toString().trimRight().split('\n');
1206
  if (kIsWeb && lines.isNotEmpty) {
1207 1208 1209
    // Remove extra call to StackTrace.current for web platform.
    // TODO(ferhat): remove when https://github.com/flutter/flutter/issues/37635
    // is addressed.
1210 1211
    lines = lines.skipWhile((String line) {
      return line.contains('StackTrace.current') ||
1212
             line.contains('dart-sdk/lib/_internal') ||
1213 1214
             line.contains('dart:sdk_internal');
    });
1215
  }
1216
  if (maxFrames != null) {
1217
    lines = lines.take(maxFrames);
1218
  }
1219 1220
  debugPrint(FlutterError.defaultStackFilter(lines).join('\n'));
}
1221

1222
/// Diagnostic with a [StackTrace] [value] suitable for displaying stack traces
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
/// as part of a [FlutterError] object.
class DiagnosticsStackTrace extends DiagnosticsBlock {
  /// Creates a diagnostic for a stack trace.
  ///
  /// [name] describes a name the stacktrace is given, e.g.
  /// `When the exception was thrown, this was the stack`.
  /// [stackFilter] provides an optional filter to use to filter which frames
  /// are included. If no filter is specified, [FlutterError.defaultStackFilter]
  /// is used.
  /// [showSeparator] indicates whether to include a ':' after the [name].
  DiagnosticsStackTrace(
    String name,
1235 1236
    StackTrace? stack, {
    IterableFilter<String>? stackFilter,
1237
    super.showSeparator,
1238 1239 1240
  }) : super(
    name: name,
    value: stack,
1241
    properties: _applyStackFilter(stack, stackFilter),
1242 1243 1244 1245 1246 1247 1248
    style: DiagnosticsTreeStyle.flat,
    allowTruncate: true,
  );

  /// Creates a diagnostic describing a single frame from a StackTrace.
  DiagnosticsStackTrace.singleFrame(
    String name, {
1249
    required String frame,
1250
    super.showSeparator,
1251 1252 1253 1254 1255 1256
  }) : super(
    name: name,
    properties: <DiagnosticsNode>[_createStackFrame(frame)],
    style: DiagnosticsTreeStyle.whitespace,
  );

1257
  static List<DiagnosticsNode> _applyStackFilter(
1258 1259
    StackTrace? stack,
    IterableFilter<String>? stackFilter,
1260
  ) {
1261
    if (stack == null) {
1262
      return <DiagnosticsNode>[];
1263
    }
1264 1265 1266 1267 1268
    final IterableFilter<String> filter = stackFilter ?? FlutterError.defaultStackFilter;
    final Iterable<String> frames = filter('${FlutterError.demangleStackTrace(stack)}'.trimRight().split('\n'));
    return frames.map<DiagnosticsNode>(_createStackFrame).toList();
  }

1269 1270 1271
  static DiagnosticsNode _createStackFrame(String frame) {
    return DiagnosticsNode.message(frame, allowWrap: false);
  }
1272 1273 1274

  @override
  bool get allowTruncate => false;
1275
}
1276 1277 1278

class _FlutterErrorDetailsNode extends DiagnosticableNode<FlutterErrorDetails> {
  _FlutterErrorDetailsNode({
1279 1280 1281 1282
    super.name,
    required super.value,
    required super.style,
  });
1283 1284

  @override
1285 1286
  DiagnosticPropertiesBuilder? get builder {
    final DiagnosticPropertiesBuilder? builder = super.builder;
1287
    if (builder == null) {
1288 1289 1290
      return null;
    }
    Iterable<DiagnosticsNode> properties = builder.properties;
1291
    for (final DiagnosticPropertiesTransformer transformer in FlutterErrorDetails.propertiesTransformers) {
1292 1293 1294 1295 1296
      properties = transformer(properties);
    }
    return DiagnosticPropertiesBuilder.fromProperties(properties.toList());
  }
}