extractBoringSslError function

String? extractBoringSslError()

Formats the least recent (and most specific) error on the current thread's BoringSSL error queue, and clears the queue before returning.

Returns null if the error queue is empty.

The error queue is thread-local, and an isolate may resume on a different OS thread after an await. Call this right after the failing BoringSSL call, with no await in between, rather than from a finally that may run after one (such as the release of an async BoringArena.run).

Use ERR_clear_error() to discard errors you ignore, for example when a failed signature verification just means false. The queue is shared by every package using package:boring on that thread, so leftover errors would be reported for the next, unrelated failure.

Implementation

String? extractBoringSslError() {
  try {
    final err = bssl.ERR_get_error();
    if (err == 0) {
      return null;
    }
    const maxLen = 4096;
    final out = opensslAllocator<ffi.Char>(maxLen);
    try {
      bssl.ERR_error_string_n(err, out, maxLen);
      final data = out.cast<ffi.Uint8>().asTypedList(maxLen);
      var len = 0;
      while (len < maxLen && data[len] != 0) {
        len++;
      }
      return utf8.decode(data.sublist(0, len), allowMalformed: true);
    } finally {
      opensslAllocator.free(out);
    }
  } finally {
    bssl.ERR_clear_error();
  }
}