mirror of
https://github.com/SyncrowIOT/web.git
synced 2025-07-11 15:47:44 +00:00
75 lines
2.2 KiB
Dart
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'] ?? 'Error');
|
|
}
|
|
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 responseMessage) {
|
|
switch (statusCode) {
|
|
case 401:
|
|
case 403:
|
|
return ServerFailure(responseMessage);
|
|
case 400:
|
|
final errors = <String>[];
|
|
if (responseMessage is List) {
|
|
for (final error in responseMessage) {
|
|
errors.add(error);
|
|
}
|
|
} else {
|
|
return ServerFailure(responseMessage);
|
|
}
|
|
return ServerFailure(errors.join('\n'));
|
|
case 404:
|
|
return ServerFailure('');
|
|
case 500:
|
|
return ServerFailure(responseMessage);
|
|
default:
|
|
return ServerFailure('Opps there was an Error, Please try again!');
|
|
}
|
|
}
|
|
}
|