Search code examples
flutterdartsocketsdart-async

catchError and "try - catch" is not working (async)


My code is trying to communicate using Socket, but I can't seem to catch the exception.

I've tried these things, but they don't work and I get an exception on the IDE.

Socket socket;
try {
  socket = await Socket.connect(ip, port);
  // Instead of jumping to errorProcess(), the IDE will show an exception here...
} catch(e) {
  errorProcess(e);
}
Socket socket = await Socket.connect(ip, port).catchError((e) {
  errorProcess(e);
  // catchError says we need to return FutureOr<Socket>...
});

How can I catch exceptions?


Solution

  • Try adding SocketException for your try catch statement.

    Example Code:

    try {} on SocketException catch (e) {
          print(e);
        } catch (e) {
          print(e);
        }