The solution to the above-said problem is quite simple and straightforward and can be solved in multiple tiers, depending on the need and complexity of the scripting, and the page functionality itself.
- Catch and Intimate User In A Friendly Way
In the starting of the webpage, just append the following lines:
window.onerror = errorHandler;
var alertmsg = "There has been an internal error." +
" Please apologize for inconvenience.";
alertmsg += "\n\nPlease refresh this page and this error should go away.\n\n";
alertmsg += "If problem persists please contact site helpdesk.";
Perhaps you can extend this by opening a small custom window and displaying the error in a more friendly fashion.
- Intimate Server Back
Frameworks and environments like .NET have easier PostBack functionality, that you can make use of effectively to deal with this kind of situations. When an error occurs, you can manually call
__doPostBack(). Perhaps this function would be available only when there is a PostBack enabled control in the webpage like
AutoPostBack=true. We can effectively circumvent this issue, by having a dummy
LinkButton with no text. This will force .NET runtime to define the
__doPostBack function and we can pass error details to the dummy
Letting the Server Know ...
The essence of error handling is just not suppression. The server should be let know of the same so that an administrator can take necessary action to correct the same. For this, I am adopting a simple jQuery Ajax Post which can collect the message and post to a particular handler in the server.
Here are some of the notes regarding this serverside push:
- The jQuery can post only to the same domain from which the server has served the page.
- If some error occurs posting the message, it would not escalate because I am following a 'eat-all' approach for this snippet.
- This particular jQuery version I am using is 2.0.0 and served from Google CDN. This might not work for IE 8 and lower. So if your application needs to support, exchange this script for 1.9 or lower. And optionally you can have the jQuery packed along with your application if your application is closed source.
Whatever is the trick above, that we are using, the objective is that the visiting user is not disturbed by showing a message that a script error like 'Object Expected' has occurred to the user, who does not know what 'Object' the browser is expecting. Isn't it? I hope that the article would be a great help to Internet Application Developers worldwide to enable their applications handle client-side scripting errors gracefully.