【问题标题】:Flutter - Remove Content Type from DioError responseFlutter - 从 DioError 响应中删除内容类型
【发布时间】:2020-05-15 01:17:44
【问题描述】:

我怎样才能只显示 DioError 内容提供的消息?

例如,而不是这个:

DioError [DioErrorType.DEFAULT]: User not found!

我只想展示:

User not found!

这里是 dio 拦截器代码:

  dio.interceptors
  ..add(InterceptorsWrapper(
    onRequest: (RequestOptions options) {
      print("Dio Request");
      print(options.headers);
      print(options.data);
      print(options.contentType);
      print(options.extra);
      print(options.baseUrl + "" + options.path);
      return options;
    },
    onResponse: (Response response) {
      print("Dio Success Response");
      print(response.data);
      print(response.extra);
      return response;
    },
    onError: (DioError e) async {
      print("Dio Error Response");
      print(e.response);
      print(e.message);
      print(e.type);
      await _errorResponseCheck(e);
    },
  ))

  _errorResponseCheck(DioError e) {
    if (e.response.data["message"] != null) {
      throw HttpException(e.response?.data["message"]?.toString());
    } else {
      return e;
    }
  }

【问题讨论】:

  • e.message 会给你错误信息。
  • 或者只是得到这样的错误print(e.message.split(":").last);
  • 现在我更新了我的答案,请看一下。也许它现在会对你有所帮助。

标签: android flutter dart dio


【解决方案1】:

例如,您会收到如下响应的异常

I/flutter (19222): DioError [DioErrorType.RESPONSE]: Http status error [400]
I/flutter (19222): uri: https://www.example.com/forgotpassword
I/flutter (19222): statusCode: 400
I/flutter (19222): Response Text:
I/flutter (19222): {"success":false,"message":"Invalid mail id"}

你可以从DioErrorresponse得到错误信息。

on DioError catch (e) {
  final base = BaseModel.fromJson(e.response.data);
  if (!base.success) {
    // Your error message. Invalid mail id
    print('Error Message : ${base.message}'); 
    throw NetworkException(base.message);
  }
}

【讨论】:

  • 你能检查一下拦截器吗? Catch 似乎在这里不起作用。
  • 我现在得到这个而不是消息:DioError [DioErrorType.DEFAULT]: Http status error [401]
  • 您可以根据它们的类型手动抛出错误。我不认为有任何其他方式@Farwa
猜你喜欢
  • 2020-11-20
  • 1970-01-01
  • 2021-11-26
  • 2011-05-02
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 2010-11-12
  • 2019-01-20
相关资源
最近更新 更多