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 recognise that format is being used.
    final String 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) == ': ') {
          longMessage = '${message.trimRight()}\n${fullMessage.substring(0, position - 2)}';
        }
      }
    }
    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;
}