request method
A function called when a request reaches this Link
Implementation
@override
Stream<Response> request(
Request request, [
NextLink? forward,
]) {
// Extract cancellation token from context
CancellationToken? cancellationToken;
final contextEntry = request.context.entry<CancellationContextEntry>();
if (contextEntry != null) {
cancellationToken = contextEntry.token;
}
final controller = StreamController<Response>();
// Run in a zone that handles errors from cancellation race conditions
runZonedGuarded(() async {
try {
final response = await _executeRequest(request, cancellationToken);
if (!controller.isClosed) {
controller.add(response);
controller.close();
}
} catch (error, stackTrace) {
if (controller.isClosed) {
// Stream already closed, ignore the error
return;
}
// Convert to CancelledException if the request was aborted
if (error is http.RequestAbortedException ||
(cancellationToken?.isCancelled == true &&
error is http.ClientException)) {
controller.addError(
const CancelledException('HTTP request was cancelled'),
stackTrace,
);
} else {
controller.addError(error, stackTrace);
}
controller.close();
}
}, (error, stackTrace) {
// Handle any uncaught errors from async operations
// (e.g., cancellation race conditions)
if (!controller.isClosed) {
if (error is http.RequestAbortedException ||
(cancellationToken?.isCancelled == true &&
error is http.ClientException)) {
controller.addError(
const CancelledException('HTTP request was cancelled'),
stackTrace,
);
} else {
controller.addError(error, stackTrace);
}
controller.close();
}
// If controller is closed, silently ignore the error
});
return controller.stream;
}