handleResponse<T> method
Future<void>
handleResponse<
T>( - dynamic error,
- Future<T> request(
- CancelToken cancelToken
), {
- bool showLoadingBar = true,
- bool showProgress = false,
- dynamic onSuccess,
- FutureOr<void> handleErrorCode(
- dynamic
)?,
})
Implementation
Future<void> handleResponse<T>(
dynamic error,
Future<T> Function(CancelToken cancelToken) request, {
bool showLoadingBar = true,
bool showProgress = false,
onSuccess,
FutureOr<void> Function(dynamic)? handleErrorCode,
}) async {
if (error is DioException) {
if (error.response != null && error.response!.statusCode != null) {
switch (error.response!.statusCode!) {
case 419:
errorController.add(ErrorState("Session expired"));
await UserCache().logout();
// navigatorKey.currentState!.pushNamedAndRemoveUntil(
// RoutePath.login,
// (Route<dynamic> route) => false,
// );
return;
case 422:
case 400:
final errorResponse = BaseModel.fromJson(error.response!.data);
if (errorResponse.isSuccess) {
onSuccess(errorResponse);
return;
// return Left(null);
}
if (handleErrorCode != null) {
handleErrorCode.call(error.response!.data);
return;
}
if (errorResponse.message != null &&
errorResponse.message is String) {
errorController.add(ErrorState(errorResponse.message!));
} else {
errorController.add(ErrorState.exception());
}
// return const Left(null);
case 401:
final errorResponse = ErrorResponse.fromJson(error.response!.data);
errorController.add(ErrorState(errorResponse.message!));
await UserCache().logout();
// navigatorKey.currentState!.pushNamedAndRemoveUntil(
// "LoginScene",
// (Route<dynamic> route) => false,
// );
// return const Left(null);
default:
errorController.add(ErrorState.exception());
// return const Left(null);
}
} else {
switch (error.type) {
case DioExceptionType.connectionTimeout:
case DioExceptionType.receiveTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.connectionError:
errorController.add(
ErrorState(SdkLocaleKeys.noInternetConnection.localize()),
);
// await navigatorKey.currentState!.pushNamed(RoutePath.noInternet,
// arguments: {
// 'title': title,
// 'message': message
// }).then((_) async {
// // Create a new cancel token for retry
// final retryToken = createCancelToken();
// await networkRequest(
// (CancelToken ct) => request(ct),
// showProgress: showProgress,
// showLoadingBar: showLoadingBar,
// onSuccess: onSuccess,
// cancelToken: retryToken,
// );
// });
case DioExceptionType.cancel:
// FBLogger.log("Request was cancelled.");
// return const Left(null);
case DioExceptionType.badResponse:
if (error.error.toString().contains("Certificate")) {
// Handle certificate pinning if needed
} else {
errorController.add(ErrorState.exception());
}
// return const Left(null);
default:
errorController.add(ErrorState.exception());
// return const Left(null);
}
}
} else {
errorController.add(ErrorState.exception());
// return const Left(null);
}
}