'Ignore http.post future exception

How can I ignore a future exception of a http.post call? In the following code I want to send a message to the server, but I don't care about the response:

  http.post(Uri(host: '10.0.2.2', port: 8000, path: 'log-message', scheme: 'http'),
      body: json.encode({
        'message': 'Event occurred',
      }));

If the server at that URL is not running, this exception is thrown:

SocketException (SocketException: Connection refused (OS Error: Connection refused, errno = 111), address = 10.0.2.2, port = 41874)

I can prevent this exception from being thrown by doing await on the above call and wrapping that around a try-catch, but I don't want to block. The following code still results in the above exception:

  http.post(Uri(host: '10.0.2.2', port: 8000, path: 'log-message', scheme: 'http'),
      body: json.encode({
        'message': 'Event occurred',
      }))
    .catchError((_) => http.Response('Logging message failed', 404));

ignore() and onError() have the same result.

I want ignore whatever exception http.post could throw without having to do an await, which blocks the code.



Solution 1:[1]

If you just print the error that you catched, it should't block the app.

http.post('http:/10.0.2.2/log-message',
                      body: json.encode({
                        'message': 'Event occurred',
                      }));
                    .catchError((_) => print('Logging message failed'));

Solution 2:[2]

There is no way to catch a SocketException without waiting for the result of the http.post operation, because it occurs later than the request is sent. Whether you use async/await with try/catch or .then and .catchError is your choice, but the preferred way is async/await:

Future<Response> myFunction async {
  try {
    return http.post(...);
  } on SocketException {
    // handle the exception here as you like
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Timur Turbil
Solution 2 Peter Koltai