Files
syncrow-app/lib/services/api/network_exception.dart
Mohammad Salameh cfc395e210 Refactor HTTPInterceptor and add CustomSnackBar helper
Refactor HTTPInterceptor to handle error responses and add a CustomSnackBar
helper to display snack bars. This will improve error handling and user
feedback in the application.
2024-04-15 12:02:34 +03:00

75 lines
2.2 KiB
Dart

import 'package:dio/dio.dart';
abstract class Failure {
final String errMessage;
Failure(this.errMessage);
}
class ServerFailure extends Failure {
ServerFailure(super.errMessage);
@override
String toString() {
return errMessage;
}
factory ServerFailure.fromDioError(DioException dioError) {
switch (dioError.type) {
case DioExceptionType.connectionTimeout:
return ServerFailure("Connection timeout with the Server.");
case DioExceptionType.sendTimeout:
return ServerFailure("Send timeout with the Server.");
case DioExceptionType.receiveTimeout:
return ServerFailure("Receive timeout with the Server.");
case DioExceptionType.badCertificate:
return ServerFailure("Bad certificate!");
case DioExceptionType.badResponse:
{
// var document = parser.parse(dioError.response!.data.toString());
// var message = document.body!.text;
return ServerFailure.fromResponse(dioError.response!.statusCode!,
dioError.response!.data['message']);
}
case DioExceptionType.cancel:
return ServerFailure("The request to ApiServer was canceled");
case DioExceptionType.connectionError:
return ServerFailure("No Internet Connection");
case DioExceptionType.unknown:
return ServerFailure("Unexpected Error, Please try again!");
default:
return ServerFailure("Unexpected Error, Please try again!");
}
}
factory ServerFailure.fromResponse(int? statusCode, dynamic response) {
switch (statusCode) {
case 401:
case 403:
return ServerFailure(response);
case 400:
List<String> errors = [];
if (response['message'] is List) {
for (var error in response['message']) {
errors.add(error);
}
} else {
errors.add(response['message']);
}
return ServerFailure(errors.join('\n'));
case 404:
return ServerFailure("Your request not found, Please try later!");
case 500:
return ServerFailure(response);
default:
return ServerFailure("Opps there was an Error, Please try again!");
}
}
}