How to catch SocketException using the http library?
SocketException on http
try {
} on SocketException {
}
You can change login
to be async
so that you can await the response. That allows you to catch the exception (and, for example, return null
instead of the Response
).
Future<Response> login(String user, String pwd) async {
final String authHeader = encodeBasicCredentials(user, pwd);
try {
return await get(
'http://192.168.0.100:8080/login',
headers: {
HttpHeaders.AUTHORIZATION: authHeader,
},
);
} catch (e) {
print(e);
return null;
}
}
You can check the type of the exception and treat it accordingly something like:
Future<Response> login(String user, String pwd) async {
final String authHeader = encodeBasicCredentials(user, pwd);
try {
return await get(
'http://192.168.0.100:8080/login',
headers: {
HttpHeaders.AUTHORIZATION: authHeader,
},
);
} catch (e) {
if(e is SocketException){
//treat SocketException
print("Socket exception: ${e.toString()}");
}
else if(e is TimeoutException){
//treat TimeoutException
print("Timeout exception: ${e.toString()}");
}
else print("Unhandled exception: ${e.toString()}");
}
}
Probly better off making an error handler lib, so you can just call a function like handleException(e);
on the catch block.