mirror of
https://github.com/SyncrowIOT/syncrow-app.git
synced 2025-07-15 01:35:23 +00:00

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.
64 lines
2.5 KiB
Dart
64 lines
2.5 KiB
Dart
import 'package:dio/dio.dart';
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
import 'package:syncrow_app/features/auth/bloc/auth_cubit.dart';
|
|
import 'package:syncrow_app/features/auth/model/token.dart';
|
|
import 'package:syncrow_app/navigation/navigation_service.dart';
|
|
import 'dart:async';
|
|
import 'dart:developer' as developer;
|
|
import 'package:syncrow_app/services/api/network_exception.dart';
|
|
import 'package:syncrow_app/utils/helpers/snack_bar.dart';
|
|
|
|
class HTTPInterceptor extends InterceptorsWrapper {
|
|
@override
|
|
@override
|
|
void onResponse(Response response, ResponseInterceptorHandler handler) async {
|
|
return handler.next(response);
|
|
}
|
|
|
|
@override
|
|
void onRequest(
|
|
RequestOptions options, RequestInterceptorHandler handler) async {
|
|
var storage = const FlutterSecureStorage();
|
|
var token = await storage.read(key: Token.loginAccessTokenKey);
|
|
// options.headers['Authorization'] = 'Bearer $token';
|
|
options.headers['Authorization'] = 'Bearer ${'${token!}123'}';
|
|
super.onRequest(options, handler);
|
|
}
|
|
|
|
@override
|
|
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
|
developer.log('Error Message: ${err.message}');
|
|
developer.log('Error res Code: ${err.response?.statusCode}');
|
|
developer.log('Error res Data: ${err.response?.data}');
|
|
developer.log('Error res status message: ${err.response?.statusMessage}');
|
|
|
|
ServerFailure failure = ServerFailure.fromDioError(err);
|
|
CustomSnackBar.displaySnackBar(failure.toString());
|
|
var storage = const FlutterSecureStorage();
|
|
var token = await storage.read(key: Token.loginAccessTokenKey);
|
|
if (err.response?.statusCode == 401 && token != null) {
|
|
await AuthCubit.get(NavigationService.navigatorKey.currentContext!)
|
|
.logout();
|
|
super.onError(err, handler);
|
|
}
|
|
}
|
|
|
|
/// Validates the response and returns true if it is successful (status code 2xx).
|
|
Future<bool> validateResponse(Response response) async {
|
|
if (response.statusCode != null) {
|
|
if (response.statusCode! >= 200 && response.statusCode! < 300) {
|
|
// If the response status code is within the successful range (2xx),
|
|
// return true indicating a successful response.
|
|
return true;
|
|
} else {
|
|
// If the response status code is not within the successful range (2xx),
|
|
// return false indicating an unsuccessful response.
|
|
return false;
|
|
}
|
|
} else {
|
|
// If the response status code is null, return false indicating an unsuccessful response.
|
|
return false;
|
|
}
|
|
}
|
|
}
|