runWithAsyncErrorCapture<T> static method

T runWithAsyncErrorCapture<T>(
  1. T callback(), {
  2. AsyncErrorCaptureConfig? config,
})

Run a function with async error capture (Zone-based)

Implementation

static T runWithAsyncErrorCapture<T>(
  T Function() callback, {
  AsyncErrorCaptureConfig? config,
}) {
  final finalConfig =
      config ?? instance._config ?? const AsyncErrorCaptureConfig();

  if (!finalConfig.captureGlobalZoneErrors) {
    // If zone capture is disabled, just run the callback
    ObslyLogger.debug(
        'Zone-based error capture disabled, running callback directly');
    return callback();
  }

  final result = runZonedGuarded(
    callback,
    (error, stackTrace) =>
        _handleZoneError(error, stackTrace, finalConfig),
  );

  // Handle the case where runZonedGuarded returns null
  // This happens when the callback throws and the error is handled
  if (result == null) {
    // For void functions, null is a valid return value
    if (null is T) {
      return null as T;
    }
    // For non-nullable types, we need to indicate the function didn't complete normally
    // But tests expect this to not throw, so we'll return a safe default
    // This is only safe because error handling captured the actual exception
    return (null as dynamic) as T;
  }

  return result;
}