Flutter:Dio HTTP处理错误异常404

时间:2019-08-13 08:44:47

标签: flutter dart

我的期望

It's using Http.get

我在处理异常 DIO 包时遇到问题,我尝试在 HTTP 包中使用此代码:

 Future<List<Mosque>> getMahasiswaById(String id) async{
       try {
         var apiRespon = await http.get('$baseURL/mahasiswa/get/id/$id');
        if(apiRespon.statusCode == 200){
            final apiResponJson = json.decode(apiRespon.body);
            return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();
        }else{
          print(apiRespon.statusCode.toString());
            throw Exception('Failed Load Data with status code ${apiRespon.statusCode}');
        }
       }on Exception catch (e) {
         print(e);
         return null;
       }
  }

但是如果我使用 DIO 进行更改,即使我已经在处理此异常,我的应用也会突然崩溃并显示错误Exception:

 Future<List<Mosque>> getMahasiswaById(String id) async{
       try {
         var apiRespon = await dio.get('$baseURL/mahasiswa/get/id/$id');
        if(apiRespon.statusCode == 200){
            final apiResponJson = apiRespon.data;
            return (apiResponJson['data'] as List).map((p)=>Mosque.fromJson(p)).toList();
        }else{
          print(apiRespon.statusCode.toString());
            throw Exception('Failed Load Data with status code ${apiRespon.statusCode}');
        }
       }on DioError catch (e) {
         print(e);
         return null;
       }
  }

我的例外:

  

error:null
  消息:“ HTTP状态错误[404]”
  响应({“ status”:false,“ message”:“未找到数据”})

我已经在github中打开问题,但尚未获得解决方案。

谢谢

This is my exception

3 个答案:

答案 0 :(得分:0)

在使用http包的第一个代码中,如果状态代码不是200,则引发Exception被捕获

on Exception catch (e) { ... }

但是,在第二个带有DIO包的代码中,您引发了相同的Exception,但是在更改捕获条件时无法捕获它

on DioError catch (e) { ... }

由于此异常未引起注意,因此它会通过您的应用传播。

答案 1 :(得分:0)

statusCode <> 200时,您可以使用.catchError()捕获异常

Future<void> _postRequest() async {
    ...
    await RequestUtil().post(path, data: data)
        .then(_handleDioResponse)
        .catchError(_handleDioError);
}

void _handleDioResponse(dynamic response){
    ...
}

void _handleDioError(dynamic error){
    ...
}

答案 2 :(得分:-1)

您可以使用.catchError()捕获异常:

dio.post().then(){ }.catchError(){ }

try catch无效。 查看更多:https://github.com/flutterchina/dio/issues/398