Smartlet error handling
Smartlets share error handling basics with other macros, but there's a bit more to it because of the 'dual rendering' aspect: when called as translation code, the standard rules apply. Simply define an "error" parameter and its code will be executed whenever an error occurs. In ajax callback mode however, the Smartlet builds a Json object which is transferred to the client. The client framework then updates the client-side state of the Smartlet. Now, in this scenario, how should we handle errors that occur on the server?
No error handling
When nothing is done, exceptions on the server are simply sent to the client as a Json object, and re-thrown there as Javascript errors. Only a global Javascript error handler will be able to catch them.
Using the AjaxError property
The AjaxError property is the counterpart of the Error property: it provides a way to suppress exceptions and provide the end-user with a message saying what went wrong. Note that when using the Error property, the AjaxError property is automatically set to a default value to ensure symmetry in exception handling on server and client.
When setting AjaxError to a non-empty value, the exception will be suppressed and the Ready handler for Ajax calls will be called with a first parameter holding an object with some exception details:
- lastError
- lastErrorType
- lastErrorMessage
- lastErrorCode
Note that setting the Error property will internally set the AjaxError property to a default value if not otherwise specified. This is done to create symmetry in error handling on client and server: if a server-side error occurs during normal rendering, the SXML in the Error property will be evaluated; If an error occurs during ajax callbacks on the server, 'normal' calling of the ready handler in the client continues, with the lastError properties set in the object passed to it.
Using a client-side error handler
The best way to handle server-side exceptions that occur during Ajax callbacks is to set up an error handler for each Ajax call:
Copy Code | |
---|---|
smartlet.set('action', 'getdata'); smartlet.ajax({ busy: true, ready: function(x){ alert(smartlet.get('data')); }, error: function(ex){ $j("#error").html(ex.lastError) }, }); |