如何在Flutter dart中获得API错误消息

wj8zmpe1  于 2023-02-05  发布在  Flutter
关注(0)|答案(1)|浏览(134)

在flutter中调用rest api时,是否可能得到错误消息?
例如:
打印(响应.状态代码);- -返回代码
如何打印此错误消息?

The request could not be processed because an error occurred whilst attempting to evaluate the SQL statement associated with this resource. Please check the SQL statement is
mlmc2os5

mlmc2os51#

如果你使用的是dio包,你可以捕获DioError并从错误中获取一个响应。在我的例子中,back返回消息['error']['' message]。我不确定它如何与http包一起工作。首先你可以打印e.response!.data来查看结构,然后获取错误文本

try {
//make request
} on DioError catch (e, stacktrace) {
  final result = e.response!.data as Map<String, dynamic>;
  print(result['error']['message']); <---- getting error message from response 
}

相关问题