handleResponse<T> method
NyResponse<T>
handleResponse<T>(
- Response response, {
- dynamic handleSuccess(
- NyResponse<
T> response
- NyResponse<
- dynamic handleFailure(
- NyResponse<
T> response
- NyResponse<
Handles an API network response from Dio.
Returns a comprehensive NyResponse object containing the original Dio Response,
morphed data, and useful utilities.
This method provides access to:
- The original Dio Response object with headers, status codes, etc.
- Morphed/decoded data using your decoders
- Utility methods for checking response status
- Raw response data
Example usage:
NyResponse<User> response = handleResponse<User>(dioResponse);
if (response.isSuccessful) {
User? user = response.data;
print('Status: ${response.statusCode}');
print('Headers: ${response.headers}');
} else {
print('Error: ${response.statusMessage}');
}
handleSuccess callback is called when response is successful (2xx status)
handleFailure callback is called when response is not successful
Implementation
NyResponse<T> handleResponse<T>(
Response response, {
Function(NyResponse<T> response)? handleSuccess,
Function(NyResponse<T> response)? handleFailure,
}) {
T? morphedData;
bool isSuccessful =
response.statusCode != null &&
response.statusCode! >= 200 &&
response.statusCode! < 300;
// Skip morphing if a callback will handle the response
bool skipMorph =
(isSuccessful && handleSuccess != null) ||
(!isSuccessful && handleFailure != null);
if (!skipMorph) {
if (T.toString() != 'dynamic') {
morphedData = _morphJsonResponse<T>(response.data);
} else {
morphedData = response.data as T?;
}
}
// Create the enhanced response object
NyResponse<T> nyResponse = NyResponse.fromResponse(
response: response,
morphedData: morphedData,
);
// Handle success callback
if (nyResponse.isSuccessful && handleSuccess != null) {
dynamic result = handleSuccess(nyResponse);
if (result == null) return nyResponse;
if (result is NyResponse<T>) return result;
return NyResponse<T>(
response: nyResponse.response,
data: result as T,
rawData: nyResponse.rawData,
);
}
// Handle failure callback
if (!nyResponse.isSuccessful && handleFailure != null) {
dynamic result = handleFailure(nyResponse);
if (result == null) return nyResponse;
if (result is NyResponse<T>) return result;
return NyResponse<T>(
response: nyResponse.response,
data: result as T,
rawData: nyResponse.rawData,
);
}
return nyResponse;
}