Created
November 7, 2022 10:11
-
-
Save sinnoorc/81723ae2d988b1eafae6cc52182afd5b to your computer and use it in GitHub Desktop.
Api Exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:dio/dio.dart'; | |
class ApiException implements Exception { | |
ApiException.fromDioError(DioError dioError) { | |
switch (dioError.type) { | |
case DioErrorType.cancel: | |
message = "Request to API server was cancelled"; | |
break; | |
case DioErrorType.connectTimeout: | |
message = "Connection timeout with API server"; | |
break; | |
case DioErrorType.receiveTimeout: | |
message = "Receive timeout in connection with API server"; | |
break; | |
case DioErrorType.response: | |
message = _handleError( | |
dioError.response?.statusCode, | |
dioError.response?.data, | |
); | |
break; | |
case DioErrorType.sendTimeout: | |
message = "Send timeout in connection with API server"; | |
break; | |
case DioErrorType.other: | |
if (dioError.message.contains("SocketException")) { | |
message = 'No Internet'; | |
break; | |
} | |
message = "Unexpected error occurred"; | |
break; | |
default: | |
message = "Something went wrong"; | |
break; | |
} | |
} | |
late String message; | |
@override | |
String toString() => message; | |
String _handleError(int? statusCode, dynamic error) { | |
switch (statusCode) { | |
case 400: | |
return 'Bad request'; | |
case 401: | |
return 'Unauthorized'; | |
case 403: | |
return 'Forbidden'; | |
case 404: | |
return error['error']; | |
case 500: | |
return 'Internal server error'; | |
case 502: | |
return 'Bad gateway'; | |
default: | |
return 'Oops something went wrong'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment