Flutter API await调用在错误时未处理响应。

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

Flutter API await calls not processing response on error

问题

I'm facing challenges getting specific API errors when I make an invalid API call from my flutter app. When the request is valid the code runs as expected. Here is the flutter/dart code I'm using:

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');
    }
}

The code doesn't seem to evaluate the statements after 'await dio.post()' when there is an invalid call.
For instance, if I put the wrong date format, it jumps straight to the catch section.
The error I get is:

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---

I would have expected to see the response code and the response data as per the print statements given. This makes it impossible for me to evaluate the errors and correct my code appropriately. If I put the correct date format, the print statements are executed.

I tested the API using curl, and the response is descriptive as expected:

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."]}

I'm running (Run Without Debugging on VS Code) the app on Chrome (web-javascript), not an emulator.

英文:

I'm facing challenges getting specific API errors when I make an invalid API call from my flutter app. When the request is valid the code runs as expected. Here is the flutter/dart code I'm using:

Future&lt;void&gt; postData() async {
    final String apiUrl = &#39;http://localhost:8000/api/&#39;;

    final Map&lt;String, dynamic&gt; requestData = {
      &quot;task_name&quot;: taskController.text,
      &quot;task_start_date&quot;: startDateController.text,
    };

    print(requestData);

    final jsonData = json.encode(requestData);

    try {
      dio.options.baseUrl = apiUrl;
      dio.options.headers = {&#39;Content-Type&#39;: &#39;application/json&#39;};

      final Response response = await dio.post(&#39;tasks/&#39;, data: jsonData);

      print(&#39;Response status code: ${response.statusCode}&#39;);
      print(&#39;Response data: ${response.data}&#39;);

      if (response.statusCode == 200) {
        print(&#39;API request successful&#39;);
        print(response.data);
      } else {
        print(&#39;API request failed with status code: ${response.statusCode}&#39;);
        print(response.data);
      }
    } catch (error) {
      print(&quot;Error checkpoint&quot;);
      print(&#39;Error: $error&#39;);
        }
    }

The code doesn't seem to evaluate the statements after 'await dio.post()' when there is an invalid call.
For instance, if I put wrong date format, it jumps straight to the catch section.
The error I get is:

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---

I would have expected to see the response code and the response data as per the print statements given. This makes it impossible for me to evaluate the errors and correct my code appropriately. If I put the correct date format the print statements are executed.

I tested the api using curl and the response is descriptive as expected:

curl -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{
    &quot;task_title&quot;: &quot;My Task&quot;,
    &quot;task_start_date&quot;: &quot;20233-06-15&quot; 
}&#39;  http://localhost:8000/api/tasks/ 
{&quot;task_start_date&quot;:[&quot;Date has wrong format. Use one of these formats instead: YYYY-MM-DD.&quot;]}

I'm running (Run Without Debugging on VS Code) the app on Chrome (web-javascript), not emulator

答案1

得分: 1

Focus on on dio.DioError part on try-catch block. If you don't handle dioerrors properly, it will throw exception and you can not get any response from it. Handle DioError by its DioErrorType.
In my case some values of DioErrorType are ;

dio.DioErrorType.response, dio.DioErrorType.receiveTimeout

bool conn = await InternetConnectionChecker().hasConnection;

if (!conn) {
return dio.Response(
requestOptions: dio.RequestOptions(
path: uri,
),
statusCode: 503);
}

String? token = devStorage.getKeysValue(tokenKey);

Map<String, dynamic>? headersw = {};

try {
dio.Response response = await dioD.delete(uri,
data: datax,
queryParameters: query ?? null,
options: dio.Options(
contentType: dio.Headers.jsonContentType,
responseType: dio.ResponseType.json,
headers: headersw,
));
print('\x1B[31m${response.data.toString()}\x1B[0m');

//print('\x1B[31m${response.data.toString()}\x1B[0m');
return response;
} on dio.DioError catch (dioerror) {

return dioerror.response;
} catch (e) {
print('\x1B[31m Error on delete: ${e.toString()}\x1B[0m');
return dio.Response(
requestOptions: dio.RequestOptions(
path: uri,
),
statusCode: 1);
}

英文:

Focus on on dio.DioError part on try-catch block. If you don't handle dioerrors properly, it will throw exception and you can not get any response from it. Handle DioError by its DioErrorType.
In my case some values of DioErrorType are ;

> dio.DioErrorType.response, dio.DioErrorType.receiveTimeout

      bool conn = await InternetConnectionChecker().hasConnection;

if (!conn) {
  return dio.Response(
      requestOptions: dio.RequestOptions(
        path: uri,
      ),
      statusCode: 503);
}

String? token = devStorage.getKeysValue(tokenKey);

Map&lt;String, dynamic&gt;? headersw = {};

try {
  dio.Response response = await dioD.delete(uri,
      data: datax,
      queryParameters: query ?? null,
      options: dio.Options(
        contentType: dio.Headers.jsonContentType,
        responseType: dio.ResponseType.json,
        headers: headersw,
      ));
  print(&#39;\x1B[31m${response.data.toString()}\x1B[0m&#39;);

  //print(&#39;\x1B[31m${response.data.toString()}\x1B[0m&#39;);
  return response;
} on dio.DioError catch (dioerror) {

  return dioerror.response;
} catch (e) {
  print(&#39;\x1B[31m Error on delete: ${e.toString()}\x1B[0m&#39;);
  return dio.Response(
      requestOptions: dio.RequestOptions(
        path: uri,
      ),
      statusCode: 1);
}

huangapple
  • 本文由 发表于 2023年6月15日 04:00:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477156.html
匿名

发表评论

匿名网友

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

确定