handleError function

dynamic handleError(
  1. Object error, [
  2. StackTrace? trace
])

Implementation

dynamic handleError(Object error, [StackTrace? trace]) {
  L.e('handleError: $error, trace: $trace');
  final locale = gNavigatorKey.currentContext == null
      ? null
      : Localizations.localeOf(gNavigatorKey.currentContext!);
  final isEnglish = locale?.languageCode == 'en';
  const color = CupertinoColors.systemRed;
  if (error is DioError) {
    String? message = error.message;
    switch (error.type) {
      case DioErrorType.cancel:
        message = isEnglish ? error.message : '取消请求';
        break;
      case DioErrorType.sendTimeout:
      case DioErrorType.connectionTimeout:
      case DioErrorType.receiveTimeout:
        message = isEnglish ? error.message : '网络连接超时,请稍后重试';
        break;
      case DioErrorType.badResponse:
        final statusCode = error.response?.statusCode;
        if (statusCode != null) {
          if (statusCode >= 400 && statusCode <= 417) {
            message = isEnglish ? error.message : '访问地址异常,请稍后重试 $statusCode';
          } else if (statusCode >= 500 && statusCode <= 505) {
            message = isEnglish ? error.message : '服务器繁忙 $statusCode';
          }
        }
        break;
      default:
        message = isEnglish ? error.message : '网络不给力,请稍后重试 $_kDioOther';
    }
    toast(message, backgroundColor: color);
  } else if (error is String) {
    toast(error, backgroundColor: color);
  } else if (error is SocketException) {
    toast(
      isEnglish ? error.message : '网络不给力,请稍后重试 $_kSocketException',
      backgroundColor: color,
    );
  } else if (error is HttpException) {
    toast(
      isEnglish ? error.message : '网络不给力,请稍后重试 $_kSocketException',
      backgroundColor: color,
    );
  } else if (error is BizException) {
    toast(error.message);
  } else if (error is PlatformException) {
    toast(
      '${error.message ?? error.toString()} ${error.code}',
      backgroundColor: color,
    );
  } else {
    if (handleCustomError != null) {
      handleCustomError!(error);
    } else {
      toast(
        isEnglish ? 'Unknown Error' : '遇到未知错误 $error',
        backgroundColor: color,
      );
    }
  }
  // catchError要求一个和Future一样类型的返回值, 但是这里无法提供一个通用的, 只能返回null了
  // 参考 http://5.9.10.113/66396293/the-return-type-void-isnt-assignable-to-futureordirectory-as-required-by
  return null;
}