response method
Starts the request and provides a IResponse.
Implementation
@override
Future<IResponse> response(Request request) async {
if (_module.coreClient.closed) {
throw MethodDisabledException(
Constants.clientIsClosed,
);
}
_logger.info(
'($_id) Preparing request.',
);
var headers = <String, String>{};
if (request.headers != null) {
headers.addAll(request.headers!);
}
var uri = prepareUri(_module.getOrigin(), request.uri ?? Uri());
if (request.body != null) {
headers.addAll(
{
'Content-Type': 'application/json; charset=utf-8',
},
);
}
_logger.info(
'($_id) Starting request to "$uri"...',
);
try {
if (isCancelled) {
throw await cancelReason;
}
final httpRequest = _prepareRequest(
request.body,
http.Request(
request.type.method,
uri,
),
headers,
);
http.StreamedResponse httpResponse;
_sendTimeoutTimer = Timer(
Duration(
milliseconds: request.type.sendTimeout,
),
() {
if (!isDone) {
_cancel.complete(
RequestTimeoutException(),
);
if (_abortRequest != null) {
_abortRequest!(
RequestTimeoutException(),
);
}
}
},
);
httpResponse = await _httpClient.send(httpRequest);
var response = Response(
httpResponse,
await httpResponse.stream.bytesToString(),
);
if (httpResponse.statusCode < 200 || httpResponse.statusCode > 299) {
throw RequestFailureException(response);
}
_logger.shout(
'($_id) Request succeed!',
);
return response;
} on RequestCancelException {
rethrow;
} on RequestFailureException {
rethrow;
} on RequestTimeoutException {
rethrow;
} catch (e) {
_logger.fatal(
'($_id) Request failed (${e.runtimeType}) ($e)',
);
throw RequestOtherException(e);
} finally {
if (!_isReleased) {
_isReleased = true;
_httpClient.close();
_sendTimeoutTimer?.cancel();
_logger.info(
'($_id) Resource released...',
);
}
}
}