Sep 26, 2014

How to handle uncaught client side exceptions in GWT?

Sometimes it gets tricky to handle client side exceptions in GWT. I have been to such situations many times before where you would expect everything to work perfectly but you found something is not working. Sometimes even no logs gets generated. It gets really hard to debug apps then.  GWT.UncaughtExceptionHandler serves that purpose for you. This interface is used to catch exceptions at the "top level" just before they escape to the browser. In development mode, the default handler prints the stack trace to the log file while in production mode, default handler is null and thus exceptions are escaped and can be troubleshooted by JavaScript debugger.  Below is a simple code snipped to create a handler for all uncaught
exceptions in a module.

 
public class ModuleEntryPoint implements EntryPoint { public void onModuleLoad() { GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() { public void onUncaughtException(Throwable e) { // Handle exceptions } // code to load module } } }
Interesting point to note here is custom UncaughtExceptionHandler will only be in effect after control from onModuleLoad is returned. Thus exceptions thrown by the "// code to load module" block will not be handled. Scheduler.ScheduledCommand can be used to handle such cases. Following is the code snippet:
 
Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { // write code to load module here Scheduler.get().scheduleDeferred(this); // reschedule } });

Hopefully above code snippet helps. Post you queries in the comment section.

If you like the post, don't forget to Follow Java Territory at Google+ to stay updated.



0 comments:

Post a Comment