用Dio / bloc Flutter处理错误

时间:2019-09-16 13:14:00

标签: flutter error-handling bloc

在使用Dio请求时,我需要一种处理错误的好方法。 我可以在一堂课中完成并通过dio请求将其抛出吗? 并且它应该返回带有错误的响应。

1 个答案:

答案 0 :(得分:0)

我在这里发布了我的广义网络集团,该集团可以在任何时间,任何地点重复使用。此外,它使用API​​仓库中的dio进行异常和错误处理。

class NetworkBloc extends Bloc<NetworkEvent, NetworkState> {
  NetworkBloc() : super(NetworkRequestInitial());

  @override
  Stream<NetworkState> mapEventToState(
    NetworkEvent event,
  ) async* {
    yield NetworkRequestInitiated();
    if (event is NetworkCallEvent) {
      RequestType requestType = event.requestType;
      if (requestType == RequestType.GET) {
        yield* fetchData(event);
      } else if (requestType == RequestType.POST) {
        yield* uploadDataAndStoreResult(event);
      }
    }
  }

  Stream<NetworkState> fetchData(NetworkCallEvent event) async* {
    Response response;
    try {
      yield NetworkRequestLoading();
      response =
          await event.apiRepository.sendGetRequest(event.url, event.request);
      if (response.statusCode == 200) {
        yield NetworkRequestLoaded(response: response);
      } else {
        Map jsonResponse = jsonDecode(response.data);
        yield NetworkRequestFailure(message: jsonResponse['message']);
      }
    } catch (e) {
      yield NetworkRequestFailure(
          message: NetworkUtils.getErrorMessageAccordingToError(e));
    }
  }

  Stream<NetworkState> uploadDataAndStoreResult(NetworkCallEvent event) async* {
    Response response;
    try {
      yield NetworkRequestLoading();
      if (event.request != null) {
        if (event.isHeadersNeeded) {
          response = await event.apiRepository.sendPostRequestWithHeader(
            event.url,
            request: event.request,
          );
        } else {
          response = await event.apiRepository.sendPostRequest(
            event.url,
            event.request,
          );
        }
      } else {
        response = await event.apiRepository
            .sendPostRequestWithoutBodyParameters(event.url);
      }
      if (response.statusCode == 200) {
        saveDataAccordingToCacheMechanism(event, response);
        yield NetworkRequestLoaded(response: response);
      } else {
        Map jsonResponse = jsonDecode(response.data);
        yield NetworkRequestFailure(message: jsonResponse['message']);
      }
    } catch (e) {
      yield NetworkRequestFailure(
          message: NetworkUtils.getErrorMessageAccordingToError(e));
    }
  }

  void saveDataAccordingToCacheMechanism(
      NetworkCallEvent event, Response response) async {
    if (event.cacheMechanism == CacheMechanism.SharePreferences) {
      Hive.box(ConstUtils.dbName)
          .put(event.keyForSharedPreferences, response.data.toString());
    } else if (event.cacheMechanism == CacheMechanism.Database) {}
  }
}

我还添加了状态和事件,以使其更易于理解。

class NetworkCallEvent extends NetworkEvent {
  final String request;
  final dynamic url;
  final RequestType requestType;
  final CacheMechanism cacheMechanism;
  final String keyForSharedPreferences;
  final APIRepository apiRepository;
  final bool isHeadersNeeded;

  NetworkCallEvent(
      {@required this.url,
      this.request,
      this.isHeadersNeeded = false,
      @required this.requestType,
      @required this.apiRepository,
      @required this.cacheMechanism,
      this.keyForSharedPreferences});

  @override
  List<Object> get props => [
        this.url,
        this.request,
        this.requestType,
        this.cacheMechanism,
        this.keyForSharedPreferences,
        this.apiRepository
      ];
}

网络状态:

class NetworkRequestInitial extends NetworkState {}

class NetworkRequestInitiated extends NetworkState {}

class NetworkRequestLoading extends NetworkState {}

class NetworkRequestLoaded extends NetworkState {
  final dynamic response;

  NetworkRequestLoaded({this.response});

  @override
  List<Object> get props => [this.response];
}

class NetworkRequestFailure extends NetworkState {
  final String message;

  NetworkRequestFailure({this.message});

  @override
  List<Object> get props => [this.message];
}

您可以轻松地以JSON发送请求并以动态方式获取Response,可以使用json.decode()将其转换为适当的对象。