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.

115 lines
3.4 KiB

import 'package:dio/dio.dart';
import 'package:flutter/material.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);
Get.snackbar(
'error'.tr, // 错误
entity.message ?? 'unknownError'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
return;
}
}
@override
void onError(DioException err, ErrorInterceptorHandler handler) {
switch (err.type) {
case DioExceptionType.cancel:
{
Get.snackbar(
'error'.tr, // 错误
'requestCancellation'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
}
case DioExceptionType.connectionTimeout:
{
Get.snackbar(
'error'.tr, // 错误
'connectionTimeout'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
}
case DioExceptionType.sendTimeout:
{
Get.snackbar(
'error'.tr, // 错误
'requestTimeout'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
}
case DioExceptionType.receiveTimeout:
{
Get.snackbar(
'error'.tr, // 错误
'responseTimeout'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
}
case DioExceptionType.badResponse:
{
try {
String? errMsg = err.response?.statusMessage;
Get.snackbar(
'error'.tr, // 错误
errMsg ?? 'unknownError'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
} on Exception catch (_) {
Get.snackbar(
'error'.tr, // 错误
'unknownError'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
}
}
default:
{
Get.snackbar(
'error'.tr, // 错误
err.message ?? 'unknownError'.tr,
snackPosition: SnackPosition.TOP,
backgroundColor: Colors.red.withOpacity(0.1),
colorText: Colors.red,
);
}
}
handler.next(err);
}
}