You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.9 KiB
66 lines
1.9 KiB
import 'package:dio/dio.dart';
|
|
import 'package:flutter_easyloading/flutter_easyloading.dart';
|
|
import 'package:get/get.dart' hide Response;
|
|
|
|
import 'package:get_storage/get_storage.dart';
|
|
import 'entity/base_entity.dart';
|
|
|
|
class AuthInterceptor extends Interceptor {
|
|
final GetStorage _storage = GetStorage();
|
|
|
|
@override
|
|
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
|
|
var jsonString = _storage.read<String>("logintoken");
|
|
options.headers['Authorization'] = jsonString;
|
|
handler.next(options);
|
|
}
|
|
|
|
@override
|
|
void onResponse(Response response, ResponseInterceptorHandler handler) async {
|
|
BaseEntity entity = BaseEntity.fromJson(response.data);
|
|
if (entity.code == 0) {
|
|
response.data = entity.data ?? {};
|
|
handler.resolve(response);
|
|
} else {
|
|
response.data = null;
|
|
handler.next(response);
|
|
return EasyLoading.showError(entity.message ?? 'unknownError'.tr);
|
|
}
|
|
}
|
|
|
|
@override
|
|
void onError(DioException err, ErrorInterceptorHandler handler) {
|
|
switch (err.type) {
|
|
case DioExceptionType.cancel:
|
|
{
|
|
EasyLoading.showError('requestCancellation'.tr);
|
|
}
|
|
case DioExceptionType.connectionTimeout:
|
|
{
|
|
EasyLoading.showError('connectionTimeout'.tr);
|
|
}
|
|
case DioExceptionType.sendTimeout:
|
|
{
|
|
EasyLoading.showError('requestTimeout'.tr);
|
|
}
|
|
case DioExceptionType.receiveTimeout:
|
|
{
|
|
EasyLoading.showError('responseTimeout'.tr);
|
|
}
|
|
case DioExceptionType.badResponse:
|
|
{
|
|
try {
|
|
String? errMsg = err.response?.statusMessage;
|
|
EasyLoading.showError(errMsg ?? 'unknownError'.tr);
|
|
} on Exception catch (_) {
|
|
EasyLoading.showError('unknownError'.tr);
|
|
}
|
|
}
|
|
default:
|
|
{
|
|
EasyLoading.showError(err.message ?? 'unknownError'.tr);
|
|
}
|
|
}
|
|
handler.next(err);
|
|
}
|
|
}
|
|
|