Posted in gwt, Software Engineering

7 Tips for Exception Handling in GWT | Summa Blog – Mozilla Firefox

7 Tips for Exception Handling in GWT | Summa Blog – Mozilla Firefox.

Exception handling best practices in Java are pretty straight-forward by now, and for the most part this carries over into the world of GWT (since GWT is, from the end developer’s perspective, just Java!). There are, however, a few tricks and gotchas that are important to be aware of. In this blog post I’ll describe a few that I’ve encountered, but please feel free to share your own.

Starting with the client tier and working my way to the server, here we go…

1. Handle all uncaught client-side exceptions

The first thing and simplest thing to do is to ensure that all unhandled exceptions bubbling out of the client tier are caught. You can accomplish this by registering an UncaughtExceptionHandler, like this:

  1. public class Example implements EntryPoint {  
  2.   public void onModuleLoad() {  
  3.     GWT.setUncaughtExceptionHandler(new   
  4.       GWT.UncaughtExceptionHandler() {  
  5.       public void onUncaughtException(Throwable e) {  
  6.         // do exception handling stuf  
  7.     }  
  8.     // do module loading stuff  
  9.   }    

Pretty straight-forward. What happens if you don’t set the UncaughtExceptionHandler in your application? Well, in hosted mode, the default handler will conveniently log the exception and stack trace to the console. In web mode, however, the handler is null, and so exceptions “escape” to your browser, which is likely not the user experience you’re looking for (though it does provide the opportunity to use a Javascript debugger for further diagnosis).

Also, be aware that your custom UncaughtExceptionHandler only takes effect the onModuleLoad() returns. In other words, if there was an exception raised where the comment “do module loading stuff” is in the example above, this exception would be handled using your custom UncaughtExceptionHandler that you just defined. This is a known issue, and will not be resolved. As a work-around, if you expect exceptions could be thrown within onModuleLoads(), then you can extract the guts of onModuleLoad() to another method, and invoke it using a DeferredCommand:

  1. public class Example implements EntryPoint {  
  2.   public void onModuleLoad() {  
  3.     GWT.setUncaughtExceptionHandler(new   
  4.       GWT.UncaughtExceptionHandler() {  
  5.       public void onUncaughtException(Throwable e) {  
  6.         // do exception handling stuff  
  7.       }  
  8.     });  
  9.     DeferredCommand.addCommand(new Command() {  
  10.       public void execute() {  
  11.         onModuleLoad2();  
  12.       }  
  13.     });  
  14.   }  
  16.   private void onModuleLoad2() {  
  17.     // do module loading stuff  
  18.   }  
  19. }  

2. Unravel GWT’s UmbrellaException

Once your UncaughtExceptionHandler is set, you may notice that some of the exceptions caught are instances of GWT’s UmbrellaException, rather than the actual exception thrown within your code. GWT uses UmbrellaExceptions to wrap exceptions in certain cases (loops, etc.), and it nests the root exception within it. For the purpose of easier debugging and more accurate error handling, it’s often helpful to unwrap these exceptions, like this:

  1. GWT.setUncaughtExceptionHandler(new   
  2.   GWT.UncaughtExceptionHandler() {  
  3.   public void onUncaughtException(Throwable e) {  
  4.     Throwable unwrapped = unwrap(e);  
  5.     // do exception handling stuff  
  6.   }    
  8.   public Throwable unwrap(Throwable e) {   
  9.     if(e instanceof UmbrellaException) {   
  10.       UmbrellaException ue = (UmbrellaException) e;  
  11.       if(ue.getCauses().size() == 1) {   
  12.         return unwrap(ue.getCauses().iterator().next());  
  13.       }  
  14.     }  
  15.     return e;  
  16.   }  
  17. }  

3. Log exceptions on the client

Now that you have a handler catching your rogue client side exceptions and also a handy method to unravel them to their root causes, you’ll want to actually useful with these exceptions to help developers more easily diagnose and resolve the underlying problems. While the appropriate action may differ per application (e.g. present an error dialog, email the support team, etc.), at the very least the exception should be logged. Fortunately, GWT delivers a simple but powerful solution for client-side logging, piggy-backing off of the standard java.util.logging package. Plugging a logger into the UncaughtExceptionHandler is easily accomplished:

  1. public class Example implements EntryPoint {  
  3.   private Logger logger = Logger.getLogger(“”);  
  5.   public void onModuleLoad() {  
  6.    GWT.setUncaughtExceptionHandler(new   
  7.      GWT.UncaughtExceptionHandler() {  
  8.      public void onUncaughtException(Throwable e) {  
  9.         logger.log(Level.ERROR, “Ex caught!”, e);  
  10.     }  
  11.     // do module loading stuff  
  12.   }    
  13. }  

Leveraging a helpful set of handlers that GWT provides, loggers can write to a number of different channels: development mode window, console, in-window pop-up, Firebug, and, the coup-de-gras, to the server(which I’ll cover in a bit). These channels are easily configurable via your .gwt.xml file:

  1. <inherits name=”” />  
  2. <set-property name=”gwt.logging.logLevel”   
  3.   value=”INFO” />            
  4. <set-property name=”gwt.logging.enabled”   
  5.   value=”TRUE” />   
  6. <set-property name=”gwt.logging.developmentModeHandler”   
  7.   value=”ENABLED” />    
  8. <set-property name=”gwt.logging.systemHandler”   
  9.   value=”DISABLED” />  
  10. <set-property name=”gwt.logging.popupHandler”   
  11.   value=”DISABLED” />  
  12. <set-property name=”gwt.logging.consoleHandler”   
  13.   value=”ENABLED”/>   
  14. <set-property name=”gwt.logging.firebugHandler”   
  15.   value=”ENABLED” />  

Logging in GWT is very well documented, so there’s no need to retread here.

4. Log exceptions on the server

The majority of the logging handlers write to the client side, however in a production environment this often isn’t much help to you. When your users stumble upon an error, it’s unlikely (and actually unsafe from a security perspective!) to expect them to look in client-side log files to help you diagnose the problem. Instead, your application should do this work for you, by logging all unexpected exceptions to the server. Fortunately, remote logging of this sort is as simple as enabling it in the .gwt.xml config file:

  1. <set-property name=”gwt.logging.simpleRemoteHandler”   
  2.     value=”ENABLED” />    

…and then defining the remote logging servlet in your web.xml file:

  1. <servlet>  
  2.   <servlet-name>remoteLogging</servlet-name>  
  3.   <servlet-class></servlet-class>  
  4. </servlet>  
  5. <servlet-mapping>  
  6.   <servlet-name>remoteLogging</servlet-name>  
  7.   <url-pattern>/your-gwt-module-name/remote_logging</url-pattern>  
  8. </servlet-mapping>  

Now, with one simple call to the log() method in your UncaughtExceptionHandler, the exception is sent automatically to your server log. Note, however, that by default it’s assumed that you’re using java.util.logging, which may not necessarily be the case. To hook these logs into, say, Log4J, check out SL4J.

Finally, it’s possible that instead of using GWT’s remote logging, you may want to implement a simple custom RPC to log (and possibly do other things – e.g. send email, etc.) when an unexpected exception is encountered. For example:

  1. GWT.setUncaughtExceptionHandler(new   
  2.   GWT.UncaughtExceptionHandler() {  
  3.   public void onUncaughtException(Throwable e) {  
  4.     myService.handleException(e);  
  5.   }  
  6. }  

Seems straight-forward, right? Be careful! First, not all exceptions are serializable or follow the rules of serializable (ugh!). For example, GWT’s JavascriptException inherits Serializable, but doesn’t implement a public no-arg constructor, so when you try to send this over the wire via your RPC, a run-time Serialization exception is thrown. And since this exception would be thrown inside your exception handler, it would effectively swallowed. Second, the stack trace within an exception is transient, and so is lost from client to server (so if you need it on the server side, send it as a separate parameter). Which leads me to the next tip…

5. Consider logging exception stack traces

Of course knowing that an exception occurred isn’t usually helpful unless you know exactly where it was thrown from! On the server side we take this for granted, since stack traces are typically logged by default with our exceptions. On the client side with GWT side, however, it’s not so easy. When Java code gets compiled into Javascript, it is both shrunk and obfuscated. This is obviously useful for performance and security, but from the perspective of supporting applications, it makes things much trickier. For example, instead of seeing a stack trace with method/class names and line numbers, you might get something like this:

 Unknown.Jq(Unknown Source) 
 Unknown.Tm(Unknown Source) 
 Unknown.Sm(Unknown Source)

Not too helpful! Fortunately, there are different options for how GWT compiles into Javascript which provide different amounts of information for debugging. Of course nothing in life is free; the trade-offs are security and performance. If you wanted nice clean Javascript that resembles your Java code and that produces nice clean stack traces, then you can flip the GWT compiler “style” flag to either “pretty” or “detailed”, however this would obviously increase the size the Javascript (and thus take longer to download)…and any user could more easily grock your client side code. There’s a nice compromise though, which is to provide file names and/or line numbers in your stack traces, but to keep the source code obfuscated. This can be configured in your .gwt.xml file:

  1. <set-property name=”compiler.stackMode”   
  2.      value=”emulated” />  
  3. <set-configuration-property name=”compiler.emulatedStack.recordLineNumbers”   
  4.      value=”true”/>   
  5. <set-configuration-property name=”compiler.emulatedStack.recordFileNames”   
  6.      value=”true”/>   

Note, again, that this does increase the size of your Javascript bundle. For one application I worked on, I found that just turning on the emulatedStack increased the Javascript by 30%, and turning on emulatedStack plus line numbers increased it by 100% (i.e. doubled the size!). Depending on the performance requirements of your application, this may or may not be acceptable.

Finally, it’s helpful to know that even with the obfuscated stack traces, there is still hope for hunting down mysterious exceptions. What seems like jibberish is just obfuscated code, and you can manually translate the obfuscated method names (e.g. “Jq”, “Tm”, or “Sm” from the above example) to the Java method names using the symbolMaps file that GWT generates. If only there were a way to do this programmatically…

6. Use the StackTraceDeobfuscator

GWT provides a utility class called the StackTraceDeobfuscator which (as it advertises!) deobfuscates stack traces, translating the condensed, jibberish stack trace (like above) into a one that you would expect. If you’re using GWT’s remote logger, then it helpfully uses this by default, with one caveat: it knows where to find the symbolMaps file. GWT places this in the “WEB-INF/deploy/your-app/symbolMaps” directory, and you can instruct the RemoteLoggerService to look there accordingly:

  1. <init-param>  
  2.   <param-name>symbolMaps</param-name>  
  3.   <param-value>your-app/symbolMaps</param-value</param-value>  
  4. </init-param>  

You could also call the StackTraceDeobfuscator manually, if, for example, you had your own RPC service that handled exceptions in some custom way. I wrote a simple subclass of the StackTraceDeobfuscator, and called it like this:

  1. public class LogServiceImpl extends LogService {   
  2.   public void logError(Throwable t, String stackTrace) {  
  3.     StackTraceElement[] sts = stackTraceDeobfuscator.deobfuscateStackTrace(t.getStackTrace());  
  4.     t.setStackTrace(sts);  
  6.     LOG.logError(“An error happened”, t);  
  7.   }  
  8. }  

7. Throw exceptions explicitly in RPC Services

Now, to the server side (which, thankfully, is much less tricky!). Imagine you have a simple RPC service that throws a custom exception, MyRuntimeException, which extends from RuntimeException. For example:

  1. public class MyServiceImpl extends MyService {   
  2.   public void foo() {   
  3.     throw new MyRuntimeException();  
  4.   }  
  5. }  

By Java’s rules, there is no obligation that you explicitly declare (either in the impl or interface) that foo throws MyRuntimeException. For the sake of simplicity, you may choose not to, however you might be surprised then to find that when you catch this exception in your AsyncCallback

  1. AsyncCallback<Void>() {   
  2.   public void onSuccess(void v) {  
  3.   }  
  5.   public void onFailure(Throwable t) {  
  6.     if(t instanceof MyRuntimeException) {   
  7.       // do something  
  8.     }  
  9.   }  
  10. }  

…the object t will not be an instance of MyRuntimeException, but rather an UnexpectedException. This is because GWT did not know to compile MyRuntimeException into Javascript, and so the client code does not know of this type. To remedy, make sure you explicitly throw MyRuntimeException in your service interface (but not in your Async interface!):

  1. public interface MyService {   
  2.   void foo() throws MyRuntimeException;  
  3. }  

Note that if you threw some subclass of MyRuntimeException, the instanceof check work, however be aware that GWT would then compile all concrete subclasses of MyRuntimeException, which could slow build time.

Whew…that’s it. Please share any tips you have, or let me know if you see anything awry with what I’ve written. Thanks!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s