Detect if ReceivePort has handler prior to call

Issue

I’ve got an isolate created using spawnFunction with an error handler provided and wrapping the send in a try/catch.

If I try to send to the replyTo and it doesn’t have a receive registered then it (rightfully) throws a method not found exception but I can’t figure out how to trap and handle it.

If you uncomment the recPort line it should all work fine.

echoIsolate() {
  port.receive((message, replyTo) {
    replyTo.send(message, port.toSendPort());
  });
}

bool errorHandler(IsolateUnhandledException ex) {
  print('Got error');
  return true;
}

run_tests() {
  test('bad rec', () {
    try {
    var recPort = new ReceivePort();
    //recPort.receive((message, replyTo) => print('Got echo: ${message}'));

    var isolatePort = spawnFunction(echoIsolate, errorHandler);

    isolatePort.send('message', recPort.toSendPort());
    } catch(ex) {
      print('Got exception');
    }
  });
}

Solution

Currently (as of April 2013) there is no way to handle this error. (afaik)

Two improvements would solve the problem: 1) a way to set a global exception handler, or 2) an asynchronous try/catch.

Global exception handlers are already possible if the code runs in an isolate. One can pass an exception-handler as argument to spawnFunction. We are going to improve the API of isolates but currently that’s the only way to catch uncaught exceptions.

We are thinking about asynchronous try/catch, but so far it’s not more than ideas.

Edit: Also there is the question if this should even throw, buffer, or just discard the received value.

Answered By – Florian Loitsch

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *