I have a problem when I get an error request from API (when server response 500).
I am using dio or http plugin for flutter plug in.
The problem is that flutter does not show any error.
(DIO: resp.data, HTTP: resp.body)
try this for exception handling
try {
Response response = await dio.get('https://google.com');
print(response.statusCode); // 500
print(response.data); // Contains a Dio Error object
} on DioError catch(e) {
print(e);
}
}
You will retrieve in any case a Response object. According to the DIO Handling Errors documentation, it will return a DioError Object.
// DIO Example
Response response = await dio.get('https://google.com');
print(response.statusCode); // 500
print(response.data); // Contains a Dio Error object
The HTTP package works similarly.
var url = 'https://example.com/whatsit/create';
var response = await http.post(url, body: {'name': 'doodle', 'color': 'blue'});
print(response.statusCode); // 500
print(response.body); // Error message
This means in any case you are not receiving directly an error for Flutter, you have to handle the error yourself. For example, you could throw an error, if the status code is not 200.
if(response.statusCode == 200){
// everything works as expected
} else {
throw Error();
}
Related
I'm tryng to post a comment related to ceratin document in my app. I'm using .net core api and already have a working webb app. When i send comment I get an error saying:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: DioError [DioErrorType.response]: Http status error [400]
I have web app where comment section is working just fine and object that is sent in mobile app is same as in web app. Example here :
{documentId: 45, parentId: null, text: dsafd}.
ParentId is for replying to another comment, so for new comment it should be null.
This is method for posting comment
onCommentSend() async {
Client _client = Client();
var data = {
'documentId': widget.dokumentId ?? 0,
'parentId': null,
'text': commentController.text,
};
print(data);
var res = await _dokumentiService!.addComment(data);
print(res);
if(data== true){
print('Added comment');
} else {
print('not added');
}
}
And this is service method
Future<bool> addComment(komentar) async {
final response = await _client.post('/dokumenti/insertComment', data: komentar);
if(response.statusCode == 200) {
final jsonresponse = response.data;
print(komentar);
print(komentar);
return jsonresponse;
} else {
throw Exception('failed');
print(Exception);
}
}
You need to pass data like this inside data of request :
final response = await _client.post('/dokumenti/insertComment', data: jsonEncode(komentar));
and try this
I am using http package(http: ^0.13.3) in flutter for sending request to the server.
In postman, I can send request and receive response, but in android emulator I can't receive response normally.
Curious thing is that yesterday I can receive response from server, but now I can't receive response.
when, I can receive response from server, when, I can't receive response from server.
But in postman I can receive response always well.
static Future<ResObj?> post(
String url, Map<String, String> data, String? token) async {
try {
var request = new http.MultipartRequest('POST', Uri.parse(url));
request.headers.addAll({
"Authorization": token ?? "",
"Content-Type": "multipart/form-data"
});
data.forEach((key, value) {
request.fields[key] = value;
});
var streamResponse = await request.send();
print(streamResponse);
final responseString = await streamResponse.stream.bytesToString();
if (streamResponse.statusCode == 200) {
final dynamic jsonMap = json.decode(responseString);
return ResObj(
status: true, code: streamResponse.statusCode, data: jsonMap);
} else {
return ResObj(
status: false, code: streamResponse.statusCode, error: "error");
}
} catch (e) {
print(e);
return ResObj(status: false, error: "unknown");
}
}
And postman setting is
In code, I can't receive print(streamResponse), yesterday's code is same as current.
I didn't change my code today.
In code, post function's parameters(url, data, token) are normal.
In my thought, await request.send() function is not working now, but I can't catch any error.
Server is also same status as yesterday, I swear.
Maybe, Is this because of http package?
Please help me to fix this error.
I am trying to implement a Dio interceptor so I will be able to use it with my code.
I will be using this interceptor in many places. So I thought it would make sense to put it into a class or an interface whichever is best and just extend or implement it my subclasses.
I have this so far:
class AppInterceptor {
Dio dio = Dio();
AppInterceptor() {
dio.interceptors
.add(InterceptorsWrapper(onRequest: (Options options) async {
var token = await getAuthorizationToken();
options.headers["Authorization"] = 'Bearer $token';
return options;
}, onResponse: (Response response) {
// Finally, the string is parsed into a JSON object.
//print(response.toString());
return response;
}, onError: (DioError e) {
print('somthing went wrong');
// Do something with response error
return e; //continue
}));
}
}
How do I use this in a subclass to make an http call?
I tried something like this when trying to do my http call:
Response response = await AppInterceptor.dio.post(Global.functionsUrl+'/auth/linkuseraccount/', data: {'hey': 'hello'});
print(response);
It fails each time with Unhandled Exception: DioError [DioErrorType.RESPONSE]: Http status error [403]
From my backend, I can tell that it fails because the interceptor didn't pass in the authentication header.
How should I go about this?
I'm facing HTTP error 500 while Authenticating or log in with API.
and Unable to get this error.
it was working nicely before but suddenly throwing me this HTTP error.
CODE:
The instance of Dio class:
dio() {
Dio dio = Dio();
dio.options.connectTimeout = 60000; //5s
dio.options.receiveTimeout = 60000;
return dio;
}
authenticating method:
Future<Map> authenticate({#required String username, #required String password}) async{
String url = "https://.....";
Response response;
try{
response =await dio().post(
url,
options: Options(
contentType: ContentType.parse("application/x-www-form-urlencoded"),
),
data: {
'grant_type': 'password',
'client_id':clientId,
'client_secret':clientSecret,
'username': username,
'password': password,
}
);
print("Authentication post response.dataaaaaa:${response.data}");
return response.data;
}catch(e){
print("ERROR:$e");
throw e;
}
}
Getting error in catch bloc:
DioError [DioErrorType.RESPONSE]: Http status error [500]
Http status code 500 means something wrong from your API backend?
I'm trying to authenticate using the below code and unable to succeed. It looks like the json structure is incorrect.
I've tried to check the same on native android using kotlin and it works correctly.
below are the logs
flutter: {data: {email: nelloresec#xxx.com, password: xxx}}
flutter: "{\"errors\":[]}"
flutter: http://xxx.xxx.xx
flutter: Instance of 'Response'
flutter: 400
flutter: {errors: []}
The default content-type for a body of types String, List<int> or Map<String, String> is 'text/plain' and I guess you want 'application/json'
In addition you can directly pass in the user object to the body paramater (as toJson will be invoked automatically by the json.encode()-function).
Lastly, you don't need to use both await and .then(...), await will suffice:
void userLogin(String url, User user) async {
http.Response response = await http.put(
'$url/api/login',
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
body: json.encode(user),
);
if (response.statusCode == 200) {
print(url);
print(response.statusCode);
print(json.decode(response.body));
} else {
print(json.encode(response.body));
print(url);
print(response);
print(response.statusCode);
print(json.decode(response.body));
throw Exception("Error while fetching data");
}
}