exceptionAsString method

String exceptionAsString ()

Converts the exception to a string.

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.

Implementation

String exceptionAsString() {
  String longMessage;
  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
    // newline, if we recognize that format is being used.
    final Object message = exception.message;
    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) == ': ') {
          // 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';
        }
      }
    }
    longMessage ??= fullMessage;
  } else if (exception is String) {
    longMessage = exception;
  } else if (exception is Error || exception is Exception) {
    longMessage = exception.toString();
  } else {
    longMessage = '  ${exception.toString()}';
  }
  longMessage = longMessage.trimRight();
  if (longMessage.isEmpty)
    longMessage = '  <no message available>';
  return longMessage;
}