如何在flutter中从dio得到自定义错误?

xesrikrc  于 2023-01-21  发布在  Flutter
关注(0)|答案(2)|浏览(272)

我试图从后端获得自定义错误,但DIO给我这个错误代替:
DioError [DioError类型响应]:HTTP状态错误[400]
下面是我的代码:

@override
  Future<SignUpResponseModel> registerBuyer(BuyerModel user) async {
    final response = await api.dio.post('api/users/buyer', data: user.toJson());
    if (response.statusCode == 200) {
      return response.data.value;
    } else {
      final error =
          response.data.errors[0] ?? "Error";
      throw Exception(error);
    }
  }
2uluyalo

2uluyalo1#

解决方法是在代码的catch块中添加DioError。这样我就可以管理和访问来自后端的自定义错误。

try {
      final response =
          await api.dio.post('api/users/buyer', data: user.toJson());
      if (response.statusCode == 200) {
        return response.data.value;
      } else {
        final error =
            response.data.errors[0] ?? "Error";
        throw Exception(error);
      }
    } catch (e) {
      if (e is DioError) {
        //This is the custom message coming from the backend
        throw e.response.data['errors'][0] ??
            "Error";
      } else {
        throw Exception("Error");
      }
    }
  }
zlwx9yxi

zlwx9yxi2#

像Maven一样处理Dio异常
//音频呼叫

Future<Customer> getProfileData() async {
              Dio dio = Dio();
              var options = BaseOptions(baseUrl: "YOUR_BASE_URL", headers: {
                'Content-Type': 'application/json',
              });
              dio.options = options;
            
              try {
     
               var response = await dio.get("YOUR_END_POINTS");
                return Customer.fromJson(response.data);
              } on DioError catch (e) {
                ExceptionDescriberModel exceptionDescriberModel = exceptionHandler(
                  errorFrom: "getProfileData",
                  error: e,
                );
                throw exceptionDescriberModel.message;
              }
            }

///异常处理程序

import 'dart:convert';
        import 'dart:developer';
        import 'dart:io';
        import 'package:dio/dio.dart';
        
       ExceptionDescriberModel  exceptionHandler({required dynamic error, required String? errorFrom}) {
          log("exception from $errorFrom");
          log("status Code ${error.response?.statusCode}");
          log("response ${error.response}");
          // By default value assigned
          ExceptionDescriberModel exceptionDescriberModel = ExceptionDescriberModel(
              statusCode: error.response?.statusCode ?? -1,
              message: "Something went wrong");
        
          if (exceptionDescriberModel.statusCode == 401) {
            exceptionDescriberModel.statusCode = 401;
            exceptionDescriberModel.message = "UnAuthorised";
          } else if (exceptionDescriberModel.statusCode == 400) {
            exceptionDescriberModel.statusCode = 400;
            exceptionDescriberModel.message = "Bad Request Exception";
          } else if (error.type == DioErrorType.connectTimeout ||
              error.type == DioErrorType.receiveTimeout ||
              error.type == DioErrorType.sendTimeout) {
            exceptionDescriberModel.statusCode = 408;
            exceptionDescriberModel.message = "Request timeout";
          } else if (error.error is SocketException) {
            exceptionDescriberModel.message = "No Internet Connection!";
          } else if (error.type == DioErrorType.response) {
            final response = error.response;
            try {
              if (response != null && response.data != null) {
                final Map responseData = json.decode(response.data as String) as Map;
                exceptionDescriberModel.message = responseData['message'] as String;
                exceptionDescriberModel.statusCode = response.statusCode;
              }
            } catch (e) {
              exceptionDescriberModel.message = "Something went wrong";
            }
          } else {
            exceptionDescriberModel.message = "Something went wrong";
          }
          log("Status code ${exceptionDescriberModel.statusCode} \n: message ${exceptionDescriberModel.message}");
          return exceptionDescriberModel;
        }
        
        class ExceptionDescriberModel {
          int statusCode;
          String message;
        
          ExceptionDescriberModel({required this.statusCode, required this.message});
        }

相关问题