runCaptured<T> method
Future<AttemptExecutionOutcome<T> >
runCaptured<T>({
- required Future<
T> body(), - Future<
void> beforeClose(- Object? bodyError,
- StackTrace? bodyStackTrace
Runs an attempt while preserving its body and close failures as data.
Application adapters use this form when they need to turn a failed attempt into a report. The same scope, zone, and close ordering as run is retained, so adapters do not need a second attempt boundary.
Implementation
Future<AttemptExecutionOutcome<T>> runCaptured<T>({
required Future<T> Function() body,
Future<void> Function(Object? bodyError, StackTrace? bodyStackTrace)?
beforeClose,
}) async {
if (_runStarted) {
throw StateError('An attempt execution boundary can run only once.');
}
// Claim the boundary before opening process-wide hooks. A concurrent
// second call must not enter its `finally` path and close the first run's
// scope while its body is still using those hooks.
_runStarted = true;
Object? bodyError;
StackTrace? bodyStackTrace;
T? value;
var completed = false;
Object? closeError;
StackTrace? closeStackTrace;
final closeFailures = <({Object error, StackTrace stackTrace})>[];
try {
try {
_scope.open();
value = await runZoned(body, zoneSpecification: _zone);
completed = true;
} catch (error, stackTrace) {
bodyError = error;
bodyStackTrace = stackTrace;
}
try {
await beforeClose?.call(bodyError, bodyStackTrace);
} catch (error, stackTrace) {
closeError = error;
closeStackTrace = stackTrace;
closeFailures.add((error: error, stackTrace: stackTrace));
}
try {
await _cleanup.close();
} catch (error, stackTrace) {
closeError ??= error;
closeStackTrace ??= stackTrace;
closeFailures.addAll(_cleanup.failures);
}
} finally {
try {
_scope.close();
} catch (error, stackTrace) {
closeError ??= error;
closeStackTrace ??= stackTrace;
}
final scopeFailures = _scope.closeFailures;
if (scopeFailures.isNotEmpty) {
closeFailures.addAll(scopeFailures);
} else if (closeError != null && closeFailures.isEmpty) {
closeFailures.add((error: closeError, stackTrace: closeStackTrace!));
}
}
return AttemptExecutionOutcome<T>(
value: value,
completed: completed,
bodyError: bodyError,
bodyStackTrace: bodyStackTrace,
closeError: closeError,
closeStackTrace: closeStackTrace,
closeFailures: List.unmodifiable(closeFailures),
);
}