Michael
Michael

Reputation: 33317

How to track JSNI Errors in GWT?

When I use GWT JSNI there can be errors in my JSNI JavaScript code like this:

try {
...
} catch(error) {
 console.log(error);
}

How can I track this error in the GWT logging system or with the GWT uncaughtException?

Upvotes: 1

Views: 607

Answers (2)

Thomas Broyer
Thomas Broyer

Reputation: 64561

Exceptions thrown in JSNI methods are exposed to the Java code as JavaScriptExceptions, and you can easily wrap the object caught in JS in a JavaScriptException if you need to give it to GWT APIs that need an exception (such as GWT.log).

try {
  …
} catch (e) {
  var ex = @com.google.gwt.core.client.JavaScriptException::new(Ljava/lang/Object;)(e);
  @com.google.gwt.core.client.GWT::log(Ljava/lang/String;Ljava/lang/Throwable;)("Error doing …", ex);
}

In GWT 2.6.1+ you can use JsonLogRecordClientUtil.throwableAsJson(e) to turn any exception into a String to, e.g. send it to your server or display it.

In GWT 2.6.0+ you can use GWT.reportUncaughtException to report any exception to the UncaughtExceptionHandler if any, or to the browser otherwise:

try {
  …
} catch (e) {
  var ex = @com.google.gwt.core.client.JavaScriptException::new(Ljava/lang/Object;)(e);
  @com.google.gwt.core.client.GWT::reportUncaughtException(Ljava/lang/Throwable;)(ex);
}

That said, in most case you don't need this: just let the exception propagate outside your JSNI method and catch the JavaScriptException in Java-land.

Upvotes: 5

Christian Kuetbach
Christian Kuetbach

Reputation: 16060

You can create an JSNI method log() and call

$wnd.log(JSON.stringify(error)); and log to the GWT logger.

Upvotes: 0

Related Questions