How should i use Dart Isolate unhandledExceptionCallback?

Issue

I’m trying to use Isolates in my Dart webapp but i can’t seem to make the error callback argument work.
I have a very basic code which is being run in Dartium.

import "dart:isolate";

void main() {
  print("Main.");
  spawnFunction(test, (IsolateUnhandledException e) {
    print(e);
  });
}

void test() {
  throw "Ooops.";
}

I never see anything than “Main.” printed on the console. Am i doing something wrong or is this broken right now?

Solution

The error-callback will be executed in the new isolate. Therefore it cannot be a dynamic closure but needs to be a static function.

I haven’t tested it, but this should work:

import "dart:isolate";

bool errorHandler(IsolateUnhandledException e) {
  print(e);
  return true;
}

void test() {
  throw "Ooops.";
}

void main() {
  // Make sure the program doesn't terminate immediately by keeping a
  // ReceivePort open. It will never stop now, but at least you should
  // see the error in the other isolate now.
  var port = new ReceivePort();
  print("Main.");
  spawnFunction(test, errorHandler);
}

Note: In dart2js this feature is still unimplemented. Older versions just ignored the argument. Newer versions will throw with an UnimplementedError.

Answered By – Florian Loitsch

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.