FIX_some what i tried in API Service Dart File

This commit is contained in:
sanjeev.p 2025-12-20 12:05:09 +05:30
parent bd4465caa5
commit 4dd43e1ed1

View File

@ -68,6 +68,9 @@ class ApiService {
if (response.statusCode == 200) {
return response; // return full http.Response, not Map
} else if (response.statusCode == 401) {
await clearLocalStorageAndRedirect();
return http.Response('Forbidden', 401);
} else if (response.statusCode == 403) {
await clearLocalStorageAndRedirect();
return http.Response('Forbidden', 403);
@ -130,6 +133,7 @@ class ApiService {
return response;
}
Future<Map<String, dynamic>> logoutUsingAPI(agentId) async {
// print(_token);
if (_token == null) {
@ -146,17 +150,56 @@ class ApiService {
return response;
}
// Future<Map<String, dynamic>> _handleResponse(http.Response response) async {
// if (response.statusCode == 200) {
// return jsonDecode(response.body);
// } else if (response.statusCode == 401 || response.statusCode == 403) {
// await clearLocalStorageAndRedirect();
// return {};
// } else {
// throw Exception('Failed to load data');
// }
// }
Future<Map<String, dynamic>> _handleResponse(http.Response response) async {
Map<String, dynamic> body = {};
// 1. Try to parse JSON, but don't let a parse error stop the 401 check
try {
body = jsonDecode(response.body);
} catch (e) {
debugPrint("Could not parse JSON body: $e");
}
// 2. SUCCESS
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else if (response.statusCode == 401 || response.statusCode == 403) {
return body;
}
// 3. UNAUTHORIZED / FORBIDDEN (The 401/403 Fix)
if ((response.statusCode == 401 && body['status'] == 401) || (response.statusCode == 403 && body['status'] == 403)) {
// Perform cleanup
await AuthService.clearToken();
// Redirect using global appRouter (avoids context errors)
context.go(AppRoutes.login);
// Return a structured error so the UI knows why it failed
return {'status': 401, 'message': 'Session expired or invalid'};
}
if (response.statusCode == 401 || response.statusCode == 403) {
await clearLocalStorageAndRedirect();
return {};
} else {
throw Exception('Failed to load data');
}
// 4. ALL OTHER ERRORS
throw Exception('Server Error: ${response.statusCode}');
}
Future<Map<String, dynamic>> CheckDuplicate(
BuildContext context,
String value,