使用Dio时try-catch无法拦截DioException的问题求助
各位大佬好,我遇到一个挺费解的问题:我用Dio做网络请求,已经在代码里加了try-catch来捕获DioException,但程序运行时还是会弹出来自Dio mixin的异常提示,虽然最终程序能走到catch块里输出我自定义的错误信息,但中途这个异常会导致程序暂停一下,明明我觉得代码逻辑没问题,有没有人能帮我分析下怎么解决这个问题?
我遇到的错误信息:
Exception has occurred. DioException (DioException [bad response]: This exception was thrown because the response has a status code of 401 and RequestOptions.validateStatus was configured to throw for this status code. The status code of 401 has the following meaning: "Client error - the request contains bad syntax or cannot be fulfilled"
In order to resolve this exception you typically have either to verify and fix your request code or you have to fix the server code. )
我的代码:
import 'package:dio/dio.dart'; import 'package:weather_app/models/weather_model.dart'; class WeatherService { final String apikey = "XXXXX"; final Dio dio; final String cityName; final String baseUrl = "http://api.weatherapi.com/v1/forecast.json"; WeatherService({required this.dio, required this.cityName}); Future<WeatherModel?> getWeather() async { try { final response = await dio.get( "$baseUrl?key=$apikey&q=$cityName", options: Options(validateStatus: (_) => false), ); } on DioException catch (e) { final errorMessage = e.response?.data?["error"]?["message"] ?? "Unknown error from API"; throw Exception(errorMessage); } catch (e) { print("Request failed: $e"); } return null; } }
我已经设置了validateStatus: (_) => false,按道理应该不会因为状态码触发Dio的异常了,但还是出现这个情况,实在搞不懂哪里出问题了,求各位指点!
内容来源于stack exchange

