I/flutter (23942): DioError [DioErrorType.RESPONSE]: Http status error [500] - flutter

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?

Related

Flutter DioError [DioErrorType.RESPONSE]: Http status error [403]

I get this massage:
[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception:
DioError [DioErrorType.response]: Http status error [403]
Here is loginCall method:
Future<LoginModel?> loginCall(
String email,
String password,
) async {
Map<String, dynamic> json = {"email": email, "hashPass": password};
var response = await dio.post(baseUrl + "login", data: json);
print(response.data);
print(response.statusCode);
if (response.statusCode == 200) {
var result = LoginModel.fromJson(response.data);
print("gelen response: ${response.data}");
return result;
} else {
throw Exception("Error! ${response.statusCode}");
}
}
error 403 usually means unauthorized. Therefore, you are probably entering incorrect email and password combination.

Flutter Dio interceptor: DioError [DioErrorType.DEFAULT]: Bad state: Can‘t finalize a finalized MultipartFile

Hi i'm trying refreshtoken logic in Dio interceptor. it's working fine for json body params, but its throwing DioError [DioErrorType.DEFAULT]: Bad state: Can‘t finalize a finalized MultipartFile when i tried uploading images.
onError: (DioError error) async {
// Do something with response error
if (error.response?.statusCode == 401) {
// _dio.interceptors.requestLock.lock();
Response response;
RequestOptions options = error.response.request;
response = await _dio
.post('/user/refresh', data: {"refreshToken": _refreshToken});
if (response.statusCode == 200) {
final userData = json.encode(
{
'token': response.data["accessToken"],
'tokenType': _tokenType,
'refreshToken': response.data["refreshToken"]
},
);
prefs.setString('userData', userData);
options.data = formData;
}
options.headers["Authorization"] =
"$_tokenType ${response.data['accessToken']}";
return await _dio.request(options.path, options: options);
} else {
throw error;
}
I put together a workaround for this issue which basically consists of rebuilding the FormData before retrying. It feels a bit hacky but it works. I start by passing any info I need for the reconstruction in via the "extra" map in the request options so the interceptor has access to it. Here is some pseudo code:
//original request
dioResponse = await dio.post(
'http://my/api/endpoint',
data: myOriginalFormData,
options: Options(
headers: myHeaders,
extra: {'pathToMyFile': pathToMyFile},
),
);
//and in my interceptor I use it to construct a fresh FormData that has not been finalized
final FormData newFormData = FormData.fromMap({
'file': await MultipartFile.fromFile(
requestOptions.extra['pathToMyFile'],
contentType: MediaType('application/json', 'json')),
});
//retry with the fresh FormData
return dio.request(
requestOptions.path,
data: newFormData,
options: requestOptions,
cancelToken: requestOptions.cancelToken,
onReceiveProgress: requestOptions.onReceiveProgress,
onSendProgress: requestOptions.onSendProgress,
queryParameters: requestOptions.queryParameters,
);
Anyone have thoughts on this approach? Any major downsides?

Stop showing error from HTTP or DIO request

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

I am not able to upload images and form data to rest api using DIO package in flutter

I am not able to upload image to rest api in flutter I have checked the api its working fine.
I am not able to convert the file (image) to a uploadable form, can any one help me with that?
I have run flutter doctor -v everything is fine :)
Here is the code I am using to post form data:
Future<void> uploadAccountDetails(AccountDetailsModel details) async {
var url = baseUrl + '/api/uploads/images';
try {
Dio dio = new Dio();
FormData formData = new FormData.fromMap(
{
'city': details.cityName,
'country': details.countryName,
'residence_address': details.address,
'dob': details.dob,
'id_num': details.id,
'passport_num': details.passportNo,
'driving_license_nim': details.drivingLicNo,
'user_id': 162,
'postal_code': details.postalCode,
'id_pic': await MultipartFile.fromFile(details.idPic.path,
filename: basename(details.idPic.path)),
'driving_license_pic':
await MultipartFile.fromFile(details.drivingLicPic.path,
filename: basename(
details.drivingLicPic.path,
)),
'birth_certificate': await MultipartFile.fromFile(
details.drivingLicPic.path,
filename: basename(details.birthCertPic.path),
),
'residence_permit_pic': await MultipartFile.fromFile(
details.resPermitPic.path,
filename: basename(details.resPermitPic.path),
),
'profile_pic': await MultipartFile.fromFile(details.profilePic.path,
filename: basename(details.profilePic.path)),
},
);
print(formData);
Response response = await dio.post(
url,
data: formData,
onSendProgress: (received, total) {
if (total != -1) {
print((received / total * 100).toStringAsFixed(0) + "%");
}
},
);
print(response.statusCode);
// print(response);
} catch (e) {
print(e);
throw (e);
}
}
The logs of error are as follows:
I/flutter (22523): DioError [DioErrorType.RESPONSE]: Http status error
[500] I/flutter (22523): DioError [DioErrorType.RESPONSE]: Http status
error [500]
The status error is:
I/flutter (22523): DioError [DioErrorType.RESPONSE]: Http status error
[500]
I searched this error but didnt find any solution, can anyone help me with that?
I used dio for post a file path with some other information in this way:
Dio dio = new Dio();
FormData formData = new FormData();
formData.add(
"apiKey",
"my_api_key",
);
formData.add(
"file",
"image_path",
);
Response response = await dio.post(
"https://localhost",
data: formData,
onSendProgress: (int sent, int total) {
// do something
},
).catchError((onError) {
throw Exception('something');
});

unhandled socket exception with no internet connection when i set timeout duration

I use simple method to get some data from internet 'http get request' :
`Future<UserModel> getUser(int userId) async {
UserModel user;
try {
final response = await http.get(
"$_baseUrl/users/$userId",
)
.timeout(Duration(seconds: 5))
;
user = userModelFromJson(response.body);
return user;
} on TimeoutException catch (e) {
print('$e in authentication service');
throw e;
} on SocketException catch (e) {
print('$e in authentication service');
throw e;
} catch (e) {
print('$e in authentication service');
throw e;
}
}`
but when i have no internet connection it shows me that error :
`Exception has occurred.
SocketException (SocketException: Failed host lookup:
'jsonplaceholder.typicode.com' (OS Error: No address associated with
hostname, errno = 7))`
whenever i remove the .timeout(Duration(seconds:5)) the code works perfectly ,
but the socket exception is caught after long time (15-20)seconds to show that there is no internet connection that's why i used timeout, i tried to use multiple packages (http middleware ,http helper ,retry) , i tried to use http.client and close it in finally block and the same error occurred and the app crashes
the image shows the error when the socket exception is thrown and unhandled
it catches the timeout exception as expected but then after another 10-15 seconds it throws an handled socket exception ,why it throws this socket exception and what can i do to avoid this?
If you want to implement a timeout with the http package, here is how it can be done:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as http;
Future<void> login(String email, String password) async {
final ioClient = HttpClient();
client.connectionTimeout = const Duration(seconds: 5);
final body = { 'email': email, 'password': password };
final client = http.IOClient(ioClient);
http.Response res;
try {
res = await client
.post(
'$url/login',
headers: {'Content-Type': 'application/json'},
body: jsonEncode(body));
} on SocketException catch (e) {
// Display an alert, no internet
} catch (err) {
print(err);
return null;
}
// Do something with the response...
}
You should consider using the HTTP package https://pub.dev/packages/http
as it helps cleanup your code an helps with error handling.
Here's an example of a GET request using the package :
await http.get(url).then((response) async {
// DO SOMETHING HERE
});
response.body is your data.
response.statusCode is your http status code (200, 404, 500, etc.)
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
and here's a post request with data :
var data = {
"dataset1": {
"key1": "value",
"key2": "value",
},
};
await http.post(url,
body: jsonEncode(data),
headers: {'content-type': 'application/json'}).then((response) async {
// DO SOMETHING HERE
});