如何解决400错误时无法获取数据在颤振中
我正在尝试使用我的应用程序中的 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");
}
}
解决方法
我使用 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;
}
}
,
取出try..catch
并使用此表格:
dio.post(...).then((response) {...}).catch(...)
然后您可以随意使用 response
。
您可以阅读此article
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。