Home > Back-end >  Ignore http.post future exception
Ignore http.post future exception

Time:04-18

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('http:/10.0.2.2/log-message',
                          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('http:/10.0.2.2/log-message',
                          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.

CodePudding user response:

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'));

CodePudding user response:

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
  }
}
  • Related