如何在不使用DioError格式化的情况下从API获得确切的错误响应?

huangapple go评论67阅读模式
英文:

flutter: how can I got the exact error response from API without DioError formating?

问题

我想根据API错误向用户显示不同的消息。

问题是Dio将所有409错误拦截为冲突,并每次显示相同的消息。

API错误响应是:

有没有办法在没有dioErrors的情况下使用或处理错误?

我的DioService:

...

注意:这只是我处理的POST请求。

调用API的服务

...

英文:

I want to display different messages to users based on the API error.

the problem is that Dio intercepts all 409 errors as a conflict and displays the same message every time.

I/flutter ( 4507): 🐛 12:06:44.286125 DEBUG    Global Loggy - DioError [bad response]: The request returned an invalid status code of 409.

but API error response is:

{
    "title": "PALLET_NOT_CREATED",
    "status": 409,
    "detail": "Cannot create a new pallet, the preparer has already a pallet in status IN_PROGRESS",
    "timestamp": 1686218442060,
    "developerMessage": "SOME MESSAGE ERE",
    "code": "WMS_CLT_ERR_4",
    "errors": {}
}

is there's anyway i can use or handle errors without dioErrors ?

my DioService:

...
Future<Response<JSON>> post({
    required String endpoint,
    JSON? data,
    Options? options,
    CancelToken? cancelToken,
  }) async {
    final response = await _dio.post<JSON>(
      baseUrl + endpoint,
      data: data,
      options: options,
      cancelToken: cancelToken ?? _cancelToken,
    );
    return response;
  }
...

> NOTE: THIS IS ONLY THE POST REQUEST I HANDLED ALL OTHER METHODS`

service calling API

Future<PalletModel> createPallet(int batchId) async {
    try {
      final res = await _dioService.post(
        endpoint: CommonProperties.palletsByBatchId.replaceAll(
          ":batchId",
          batchId.toString(),
        ),
        data: {},
        options: Options(
          extra: {
            'requiresAuthToken': true,
          },
        ),
      );
      return PalletModel.fromJson(res.data!);
    } catch (e) {
      logDebug('error is:');
      logDebug(e);
      rethrow;
    }
  }

答案1

得分: 1

你可以在你的 API post 调用中应用 try/catch,在捕获 DioError 后,你可以操控数据,检查响应体等。

英文:

you can apply try/cath to your api post call

Future<Response<JSON>> post({
    required String endpoint,
    JSON? data,
    Options? options,
    CancelToken? cancelToken,
  }) async {
     try {
        final response = await _dio.post<JSON>(
          baseUrl + endpoint,
          data: data,
          options: options,
          cancelToken: cancelToken ?? _cancelToken,
        return response;
    );
    }
    on DioError catch(e) {
         print(e.response!.data.toString)
   }

    
   
  }

After catching a DioError, you can manipulate data, checking response body, etc

huangapple
  • 本文由 发表于 2023年6月8日 19:09:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431219.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定