Flutter how to handle errors in async / await

Viewed 5829

I want to catch an exception if the app fails to connect to the server (If the server is turned off for example) but not sure how and didn't succeed so far.

My code:

static Future<String> communicate(String img, String size) async
{    
    String request = size.padLeft(10, '0') + img;
    Socket _socket;

    await Socket.connect(ip, 9933).then((Socket sock) 
    {
        _socket = sock;
    }).then((_)
    {
        //Send to server
        _socket.add(ascii.encode(request));
        return _socket.first;
    }).then((data)
    {
        //Get answer from server
        response =  ascii.decode(base64.decode(new String.fromCharCodes(data).trim()));
    });
    return response;    
}

Function call:

var ans = await communicate(bs64Image, size);
2 Answers

In general, you handle errors like this with async/await:

try { 
   // code that might throw an exception 
}  
on Exception1 { 
   // exception handling code 
}  
catch Exception2 { 
   //  exception handling 
}  
finally { 
   // code that should always execute; irrespective of the exception 
}

In your case, you should try something like:

try {
   var ans = await communicate(bs64Image, size);
}
catch (e){
   print(e.error);
}
finally {
print("finished with exceptions");
}

Try using SocketException if request fails exception will be thrown

import 'dart:io';

try {
  response = await get(url);
} on SocketException catch (e) {
  return e;
}
Related