Flutter使用Dio发起API请求出错时无法获取响应详情的问题
无法获取Flutter Dio无效API调用的详细错误信息
问题场景
发起无效API调用(例如输入错误日期格式)时,代码直接进入catch块,只能拿到模糊的错误提示,无法获取API返回的具体错误数据;有效请求则能正常执行并打印完整响应。
现有代码
Future<void> postData() async { final String apiUrl = 'http://localhost:8000/api/'; final Map<String, dynamic> requestData = { "task_name": taskController.text, "task_start_date": startDateController.text, }; print(requestData); final jsonData = json.encode(requestData); try { dio.options.baseUrl = apiUrl; dio.options.headers = {'Content-Type': 'application/json'}; final Response response = await dio.post('tasks/', data: jsonData); print('Response status code: ${response.statusCode}'); print('Response data: ${response.data}'); if (response.statusCode == 200) { print('API request successful'); print(response.data); } else { print('API request failed with status code: ${response.statusCode}'); print(response.data); } } catch (error) { print("Error checkpoint"); print('Error: $error'); } }
错误现象
无效调用时,await dio.post()后的代码不会执行,直接跳转到catch块,打印信息如下:
Error checkpoint Error: DioError [DioErrorType.response]: Http status error [400] Source stack: dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 942:28 ---snipped---
但通过curl测试API能获取到完整的错误响应:
curl -X POST -H "Content-Type: application/json" -d '{ "task_title": "My Task", "task_start_date": "20233-06-15" }' http://localhost:8000/api/tasks/ {"task_start_date":["Date has wrong format. Use one of these formats instead: YYYY-MM-DD."]}
运行环境:VS Code无调试模式,Chrome(web-javascript)
解决方案
方案1:在catch块中解析Dio异常
Dio默认会对非2xx状态码抛出DioException(旧版本为DioError),你可以在catch块中判断异常类型,提取响应中的详细错误信息:
catch (error) { print("Error checkpoint"); if (error is DioException) { print('Status code: ${error.response?.statusCode}'); print('Detailed error data: ${error.response?.data}'); print('Error message: ${error.message}'); } else { print('Unknown error: $error'); } }
方案2:全局配置Dio不拦截非2xx状态码
如果你希望所有状态码的响应都进入try块处理,可以修改Dio的validateStatus配置,让它不对非2xx状态码抛出异常:
// 初始化Dio时配置 dio.options.validateStatus = (status) { // 允许所有状态码都不触发异常 return status != null; };
配置后,无论响应状态码是200还是400/500,代码都会执行await dio.post()之后的逻辑,你可以在原有的状态码判断分支中处理错误信息。
内容的提问来源于stack exchange,提问作者masterl
相关产品推荐
相关产品推荐

