【问题标题】:How to handle error message from Dio post call?如何处理来自 Dio post call 的错误信息?
【发布时间】:2021-07-14 15:37:12
【问题描述】:

我是 Flutter 的新手,难以解决 api 调用。 我正在使用 Dio 库进行 api 调用。 我已经创建了一个基类来访问所有 api 方法。以下是帖子示例。

Future<Response?> postHTTP(String url, dynamic data) async {
try {
  Response response = await baseAPI().post(
    url,
    data: data,
  );
  return response;
} on DioError catch (e) {
  // Handle error
  if (e.response != null) {
    return e.response;
  }
  print(e.message);
  throw Exception(e.response?.data);
}

}

我正在通过以下方式调用我的登录 api。

Future<AuthResponse> login(Payload payload) async {
try {
  Response? response = await apiBaseHelper.postMod(
      '/login', {"email": payload.email, "password": payload.password});
  return AuthResponse.fromJson(response?.data);
} catch (e) {
  print('in repo $e');
  throw e;
  // ErrorResponse errorResponse = ErrorResponse.fromJson(e.response?.data);
  // print(errorResponse);
  // return e.response?.data;
}

    AuthResponse loginResponse = await authApi.login(payload);

我确实得到了成功的登录响应。我不知道如何提取我在错误响应中收到的消息。我曾尝试返回 error.response,但最终出现错误

我想显示一个带有错误响应消息的错误 toast。 提前致谢。

【问题讨论】:

    标签: api flutter dart dio


    【解决方案1】:

    是的... 你必须像这样检查状态码

    if (response.statusCode == 200) {
    /// your code. here 
    }else{
    you can now print the error
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-17
      • 2019-12-18
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多