handleDioError function
Implementation
ScrellaApiException handleDioError(
DioException error, {
Function(String message, int? statusCode)? setErrorMessage,
}) {
if (error.response != null) {
final statusCode = error.response?.statusCode;
final data = error.response?.data;
final message = data is Map && data['message'] != null
? data['message'].toString()
: (data is Map && data['title'] != null
? data['title'].toString()
: 'Request failed with status code $statusCode');
setErrorMessage?.call(message, statusCode);
//print("error.response?.data: ${error.response?.data?.toString()}");
//print("error.requestOptions: ${error.requestOptions.headers.toString()}");
return ScrellaApiException(message, statusCode: statusCode);
}
switch (error.type) {
case DioExceptionType.connectionTimeout:
setErrorMessage?.call(
'Connection timeout. Please try again.',
ScrellaApiErrorState.connectionTimeout.index,
);
return ScrellaApiException(
'Connection timeout. Please try again.',
statusCode: ScrellaApiErrorState.connectionTimeout.index,
);
case DioExceptionType.sendTimeout:
setErrorMessage?.call(
'Request timeout. Please try again.',
ScrellaApiErrorState.requestTimeout.index,
);
return ScrellaApiException(
'Request timeout. Please try again.',
statusCode: ScrellaApiErrorState.requestTimeout.index,
);
case DioExceptionType.receiveTimeout:
setErrorMessage?.call(
'Response timeout. Please try again.',
ScrellaApiErrorState.responseTimeout.index,
);
return ScrellaApiException(
'Response timeout. Please try again.',
statusCode: ScrellaApiErrorState.responseTimeout.index,
);
case DioExceptionType.connectionError:
setErrorMessage?.call(
'No internet connection.',
ScrellaApiErrorState.noInternet.index,
);
return ScrellaApiException(
'No internet connection.',
statusCode: ScrellaApiErrorState.noInternet.index,
);
case DioExceptionType.cancel:
setErrorMessage?.call(
'Request was cancelled.',
ScrellaApiErrorState.cancelled.index,
);
return ScrellaApiException(
'Request was cancelled.',
statusCode: ScrellaApiErrorState.cancelled.index,
);
default:
setErrorMessage?.call(
'Unexpected error occurred.',
ScrellaApiErrorState.unknown.index,
);
return ScrellaApiException(
'Unexpected error occurred.',
statusCode: ScrellaApiErrorState.unknown.index,
);
}
}