【问题标题】:Can't get data when 400 error. in Flutter400 错误时无法获取数据。在颤振中
【发布时间】:2021-06-05 08:42:39
【问题描述】:

我正在尝试在我的应用程序中使用 Dio 包实现登录。当我发送正确的电子邮件和密码时,我会收到 200 状态代码和用户数据。但是当我发送电子邮件或密码不正确时,后端会发送 400 错误代码和类似 {"message": "User Not Exist","data": [],"status": false} 的数据,问题是当我有 400 错误时我无法获取数据,因为在 dio catchError 方法中我只能得到错误和堆栈跟踪。

Future login(String username, String password) async {
    try {
      String url = "$baseUrl/admin/user/login";
      print(url);
      var res = await dio.post(
        url,
        data: {"email": username, "password": password},
      );
      if (res.statusCode == 400) {
        print(res.data); <----- This dont print anything.
        return false;
      } else {
        print(res.data);
        return true;
      }
      // await Future.delayed(Duration(seconds: 4));
    } catch (e, s) {<----- here I have just error and stacktrace not the data
      print("stacktrace $s");
      print("error $e");
    }
  }

【问题讨论】:

    标签: ajax flutter http dart dio


    【解决方案1】:

    我使用 on DioError catch 而不是 catch 方法解决了这个问题。

    Future login(String username, String password) async {
        try {
          String url = "$baseUrl/admin/user/login";
          print(url);
          var res = await dio.post(
            url,
            data: {"email": username, "password": password},
          );
          if (res.statusCode == 400) {
            print(res.data); <----- This dont print anything.
            return false;
          } else {
            print(res.data);
            return true;
          }
          // await Future.delayed(Duration(seconds: 4));
        } on DioError catch (e) {
          print(e.response.data);<-----------here I can get the data 
          return e.response.data;
        }
      }
    

    【讨论】:

      【解决方案2】:

      取出try..catch 并使用此表格:

      dio.post(...).then((response) {...}).catch(...)
      

      那么你可以随意使用response

      你可以阅读这个article

      【讨论】:

      • 这不是有效的代码。 catch 不是 Future 类的方法。
      猜你喜欢
      • 2021-12-16
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2021-03-04
      • 1970-01-01
      • 2020-02-12
      相关资源
      最近更新 更多