ericwlange/AndroidJSCore

Handle exceptions from JavaScript

simonexmachina opened this issue · 7 comments

JavaScriptCore provides an exceptionHandler property that can be used to handle exceptions generated from JavaScript. This would be really handy in AndroidJSCore.

Every call to JS can throw a JSException. If there was an exception in JavaScript it will get caught here. I understand the convenience of this feature, though. Will look into what it would take to add it.

The real value of the global exception handler is that an exception could be thrown from an event loop callback ie. setTimeout() or an AJAX request returning.

Is setTimeout() part of raw JavaScript? You may be right, I will have to check. However, AJAX is not. It is part of the DOM, which is not included in JavaScriptCore, but in WebKit. Actually, setTimeout() creates another set of issues if it is there. JS is intended to be single-threaded, so when the code finishes execution, it returns to the caller. I am not sure what thread setTimeout() would return in?

Take for example:

context.evaluateScript('setTimeout(60000,function(){ /* do something */}));

Imagine if I put this in some thread, ran this single line, and then closed the thread. This line will return immediately. I am not sure what would happen when the 60 seconds expired.

In any case, I will add it. It is useful to have in any case. I will also examine what edge cases around setTimeout() come up.

No, it appears not to be part of raw JavaScript. Regarding setTimeout() I'd say that the JavaScript event loop will run in a thread, but yes there's certainly challenges there.

I have added JSContext.setExceptionHandler(). You would add implements JSExport.IJSExceptionHandler to some object, and implement the public void handle(JSException exception) method. Then call context.setExceptionHandler(my_object). Now whenever a JSException is thrown, it will get caught here.

As a result, I changed JSException to be a subclass of RuntimeException instead of Exception, so if you set the exception handler at the JSContext level, you can get rid of all try/catch blocks.

I also added ExceptionHandlerExample.java to the example app that demonstrates how to use it.

It is not in the 2.0 release, but is on HEAD. You will have to build the library to get it. I will add it to the next release.

This is now included in 2.1. Cheers.