I want to handle http request flutter with some error message but I got so many errors here. I just make it based on the suggestion but it didn't work for me. Please, anyone, help me Here is my function to call API
getData(data, apiUrl) async {
var tempUrl = _url + apiUrl + await _getToken();
Uri uri = Uri.parse(tempUrl);
var fullUrl = uri.replace(queryParameters: data);
var res;
try {
var response = await http.get(fullUrl, headers: _setHeaders()).timeout(
const Duration(seconds: 60));
print(response.statusCode);
if (response.statusCode != 200) {
res = {
"success": false,
"status": response.statusCode,
"message": _returnResponse(response)
};
}
else {
res = response;
}
}
on SocketException {
throw FetchDataException('No Internet connection');
}
on TimeoutException catch (e) {
res = {
"success": false,
"status": response.statusCode,
"message": "Connection timeout"
};
} on Error catch (e) {
print('Error: $e');
}
return res;
}
This is my return response for the others except 200
dynamic _returnResponse(http.Response response) {
switch (response.statusCode) {
case 400:
throw BadRequestException(response.body.toString());
case 401:
case 403:
throw UnauthorisedException(response.body.toString());
case 500:
default:
throw FetchDataException(
'Error occured while Communication with Server with StatusCode : ${response
.statusCode}');
}
}
and here is my app_exception.dart I got from StackOverflow and other forums
class AppException implements Exception {
final _message;
final _prefix;
AppException([this._message, this._prefix]);
String toString() {
return "$_prefix$_message";
}
}
class FetchDataException extends AppException {
FetchDataException([String message])
: super(message, "Error During Communication: ");
}
class BadRequestException extends AppException {
BadRequestException([message]) : super(message, "Invalid Request: ");
}
class UnauthorisedException extends AppException {
UnauthorisedException([message]) : super(message, "Unauthorised: ");
}
class InvalidInputException extends AppException {
InvalidInputException([String message]) : super(message, "Invalid Input: ");
}
I have tried so many suggestions but it didn't work at all
I got this error
Error: 'SocketException' isn't a type. on SocketException { ^^^^^^^^^^^^^^^
Error: 'TimeoutException' isn't a type. on TimeoutException catch (e) { ^^^^^^^^^^^^^^^^
It is thrown when a schedule timeout happens while waiting for an async result. The main objective of the exception is to handle the run-time error and prevent the program from terminating abruptly. Every exception in the Dart is a subtype of the pre-defined class Exception.
DioError describes the error info when request failed.
Here is a step by step procedure
First of all add a http: ^0.13.4
after then following a below steps
1) Create an API base helper class
For making communication between our Remote server and Application we use various APIs which need some type of HTTP methods to get executed. So we are first going to create a base API helper class, which will be going to help us communicate with our server.
import 'CustomException.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:convert';
import 'dart:async';
import 'package:connectivity/connectivity.dart';
class APIManager {
Future<dynamic> postAPICall(String url, Map param) async {
print("Calling API: $url");
print("Calling parameters: $param");
var responseJson;
try {
final response = await http.post(url,
body: param);
responseJson = _response(response);
} on SocketException {
throw FetchDataException('No Internet connection');
}
return responseJson;
}
dynamic _response(http.Response response) {
switch (response.statusCode) {
case 200:
var responseJson = json.decode(response.body.toString());
return responseJson;
case 400:
throw BadRequestException(response.body.toString());
case 401:
case 403:
throw UnauthorisedException(response.body.toString());
case 500:
default:
throw FetchDataException(
'Error occured while Communication with Server with StatusCode: ${response.statusCode}');
}
}
}
2) Create CustomException Class
An HTTP request on execution can return various types of status codes based on its status. We don’t want our app to misbehave if the request fails so we are going to handle most of them in our app. For doing we are going to create our custom app exception which we can throw based on the response status code.
class CustomException implements Exception {
final _message;
final _prefix;
CustomException([this._message, this._prefix]);
String toString() {
return "$_prefix$_message";
}
}
class FetchDataException extends CustomException {
FetchDataException([String message])
: super(message, "Error During Communication: ");
}
class BadRequestException extends CustomException {
BadRequestException([message]) : super(message, "Invalid Request: ");
}
class UnauthorisedException extends CustomException {
UnauthorisedException([message]) : super(message, "Unauthorised: ");
}
class InvalidInputException extends CustomException {
InvalidInputException([String message]) : super(message, "Invalid Input: ");
}
3) Create a Method to fetch data from APIs
Calling API:- for fetching data from the API
void signIn(Map param) {
setState(() {
_isLoading = true;
});
apiManager.postAPICall(BASE_URL + user_login, param).then((value) {
var status_code = value["statuscode"];
if (status_code == 200) {
var userData = value["user_data"];
Navigator.push(context, PageTransition(type:
PageTransitionType.rightToLeftWithFade, child: HouseholderHomeScreen()));
setState(() {
_isLoading = false;
});
} else {
setState(() {
_isLoading = false;
});
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: new Text(value["msg"]),
backgroundColor: Colors.red,
duration: new Duration(seconds: 2),
)
);
}
}, onError: (error) {
setState(() {
_isLoading = false;
});
print("Error == $error");
_scaffoldKey.currentState.showSnackBar(
SnackBar(
content: new Text('Something went wrong..'),
duration: new Duration(seconds: 2),
)
);
print(error);
});
}
I used dio package. That's more easier and bug-less than i make it
https://pub.dev/packages/dio
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With