throwIfError method

void throwIfError()

Checks the slot after a bridge call. If an error is present: copies the string fields into Dart, frees them with the module's nitro_free, resets the slot for the next call, and throws a HybridException.

No-op (a single 20-byte read) when there is no error.

Implementation

void throwIfError() {
  final bytes = module.readBytes(ptr, sizeInBytes);
  if (bytes[0] == 0) return;
  final bd = ByteData.sublistView(bytes);
  final namePtr = bd.getUint32(4, Endian.little);
  final msgPtr = bd.getUint32(8, Endian.little);
  final codePtr = bd.getUint32(12, Endian.little);
  final stackPtr = bd.getUint32(16, Endian.little);

  final name = namePtr != 0 ? module.readCString(namePtr) : 'NativeException';
  final message = msgPtr != 0 ? module.readCString(msgPtr) : 'An unknown native exception occurred.';
  final code = codePtr != 0 ? module.readCString(codePtr) : null;
  final stack = stackPtr != 0 ? module.readCString(stackPtr) : null;

  module.nitroFree(namePtr);
  module.nitroFree(msgPtr);
  module.nitroFree(codePtr);
  module.nitroFree(stackPtr);
  module.writeBytes(ptr, Uint8List(sizeInBytes));

  throw HybridException(
    name: name,
    message: message,
    code: code,
    stackTrace: stack,
  );
}