Refactor API error handling and add try-catch blocks

Added try-catch blocks for error handling in API's files to rethrow the errors to the cubit so cubits can update the UI based on them.

Refactored error handling in HTTPInterceptor and HTTPService classes.
This commit is contained in:
Mohammad Salameh
2024-04-15 15:47:13 +03:00
parent dd90a2133f
commit df13c66b1a
9 changed files with 247 additions and 191 deletions
+21 -27
View File
@@ -41,7 +41,7 @@ class AuthCubit extends Cubit<AuthState> {
static UserModel? user;
static Token token = Token.emptyConstructor();
/////////////////////////////////////API CALLS/////////////////////////////////////
login() async {
emit(AuthLoginLoading());
try {
@@ -51,23 +51,23 @@ class AuthCubit extends Cubit<AuthState> {
password: passwordController.text,
),
);
if (token.accessTokenIsNotEmpty) {
FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.write(
key: Token.loginAccessTokenKey, value: token.accessToken);
const FlutterSecureStorage().write(
key: UserModel.userUuidKey,
value: Token.decodeToken(token.accessToken)['uuid'].toString());
user = UserModel.fromToken(token);
emailController.clear();
passwordController.clear();
emit(AuthLoginSuccess());
} else {
emit(AuthLoginError(message: 'Something went wrong'));
}
} on ServerFailure catch (failure) {
emit(AuthError(message: failure.errMessage));
} catch (failure) {
emit(AuthLoginError(message: failure.toString()));
return;
}
if (token.accessTokenIsNotEmpty) {
FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.write(
key: Token.loginAccessTokenKey, value: token.accessToken);
const FlutterSecureStorage().write(
key: UserModel.userUuidKey,
value: Token.decodeToken(token.accessToken)['uuid'].toString());
user = UserModel.fromToken(token);
emailController.clear();
passwordController.clear();
emit(AuthLoginSuccess());
} else {
emit(AuthLoginError(message: 'Something went wrong'));
}
}
@@ -79,8 +79,9 @@ class AuthCubit extends Cubit<AuthState> {
NavigationService.navigatorKey.currentState!
.popAndPushNamed(Routes.authLogin);
emit(AuthLogoutSuccess());
} on ServerFailure catch (failure) {
emit(AuthError(message: failure.errMessage));
} catch (failure) {
emit(AuthLogoutError(message: failure.toString()));
return;
}
}
@@ -109,11 +110,4 @@ class AuthCubit extends Cubit<AuthState> {
emit(AuthTokenError(message: "Something went wrong"));
}
}
static void logUserOut() async {
user = null;
token = Token.emptyConstructor();
FlutterSecureStorage storage = const FlutterSecureStorage();
await storage.delete(key: Token.loginAccessTokenKey);
}
}