processError method

void processError(
  1. Object error, [
  2. Object? externalStackTrace
])

Catch errors throwed by other code, and wrap them with detailed informations.

Implementation

void processError(Object error, [Object? externalStackTrace]) {
  final sb = StringBuffer();

  void handleStackTrace(List<String> stackTrace,
      {bool withLineNumber = false}) {
    if (errorConfig.stackTraceDisplayCountLimit > 0) {
      if (stackTrace.length > errorConfig.stackTraceDisplayCountLimit) {
        for (var i = stackTrace.length - 1;
            i >= stackTrace.length - errorConfig.stackTraceDisplayCountLimit;
            --i) {
          if (withLineNumber) {
            sb.write('#${stackTrace.length - 1 - i}\t');
          }
          sb.writeln(stackTrace[i]);
        }
        sb.writeln(
            '...(and other ${stackTrace.length - errorConfig.stackTraceDisplayCountLimit} messages)');
      } else {
        for (var i = stackTrace.length - 1; i >= 0; --i) {
          if (withLineNumber) {
            sb.write('#${stackTrace.length - 1 - i}\t');
          }
          sb.writeln(stackTrace[i]);
        }
      }
    } else if (errorConfig.stackTraceDisplayCountLimit < 0) {
      for (var i = stackTrace.length - 1; i >= 0; --i) {
        if (withLineNumber) {
          sb.write('#${stackTrace.length - 1 - i}\t');
        }
        sb.writeln(stackTrace[i]);
      }
    }
  }

  if (stackTraceList.isNotEmpty && errorConfig.showHetuStackTrace) {
    sb.writeln(HTLocale.current.scriptStackTrace);
    handleStackTrace(stackTraceList, withLineNumber: true);
  }
  if (externalStackTrace != null && errorConfig.showDartStackTrace) {
    sb.writeln(HTLocale.current.externalStackTrace);
    final externalStackTraceList =
        externalStackTrace.toString().trim().split('\n').reversed.toList();
    handleStackTrace(externalStackTraceList);
  }

  final stackTraceString = sb.toString().trimRight();
  if (error is HTError) {
    final wrappedError = HTError(
      error.code,
      error.type,
      message: error.message,
      extra: stackTraceString,
      filename: error.filename ?? currentFileName,
      line: error.line ?? currentLine,
      column: error.column ?? currentColumn,
    );
    throw wrappedError;
  } else {
    final hetuError = HTError.extern(
      _lexicon.stringify(error),
      extra: stackTraceString,
      filename: currentFileName,
      line: currentLine,
      column: currentColumn,
    );
    throw hetuError;
  }
}