英文:
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<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 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 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<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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论