Click here to Skip to main content
Click here to Skip to main content
Go to top

Graceful Handling Of JavaScript Errors

, 16 May 2013
Rate this:
Please Sign up or sign in to vote.
In this article, we would see how to gracefully handle JavaScript errors on a webpage, without creating a wrong impression in the minds of our visitors and/or users.

Introduction

In this small article, we would discuss how to gracefully handle JavaScript errors, instead of the browser dependant behavior of pointing out the errors to the visitor, who does not know much, how to deal or remedy that error. This would also facilitate us to communicate to the server that a client side script has failed and one or more of client-script manipulations might not have completed successfully and that the server needs to check those functionality again at its end.

The Scenario

JavaScript has got pretty embedded nowadays with every web page -- ranging from cosmetic and flashy document effects to user-form entry checking/confirmation etc. Perhaps if there is a client side scripting error, due to unforeseen circumstances, it would be disgusting to the user to see a 'Done but with errors on page' flashing on the window status bar. When a scripting error occurs, normally the running script function is also halted by the web browser and no further script calls are executed in that context. Perhaps, in these cases, it would be good if our script could notify back the server of its failure and also to gracefully report the error/failure condition to the user.

The Solution

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;
    
    function errorHandler(msg,url,lno)
    {
      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.";
      alert (alertmsg);
      return (true);
    }

    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 DataGrid, Checkbox/Dropdownlist with 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 LinkButton Handler.

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.  
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<Script Language="'JavaScript'" type='text/javascript'>
function LogScriptErrorsToServer(strScriptError)
{
   try
   {
   var strErrorURL = '<%# ResolveUrl("~/app/handlers/helper.ashx?type=scripterrors") %>';   
                        $.ajax({
                        type: "POST",
                        data: "scripterror="+strScriptError,
                        url: strErrorURL,
                        cache:false,
                        success: function(data)
                        {
                            
                        },
                        error:function (data)
                        {
                           
                        }
                    });  
    }
	catch (e) {}
}
</Script>   

Here are some of the notes regarding this serverside push:

  1. The jQuery can post only to the same domain from which the server has served the page.
  2. If some error occurs posting the message, it would not escalate because I am following a 'eat-all' approach for this snippet.
  3. 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. 

Conclusion 

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. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vasudevan Deepak Kumar
Software Developer
India India
Vasudevan Deepak Kumar is from Chennai, India who has been in the programming career since 1994, when he was 15 years old. He has his Bachelors of Engineering (in Computer Science and Engineering) from Vellore Engineering College. He also has a MBA in Systems from Alagappa University, Karaikudi, India.
He started his programming career with GWBasic and then in his college was involved in developing programs in Fortran, Cobol, C++. He has been developing in Microsoft technologies like ASP, SQLServer 2000.
His current focus is ASP.NET, C#, VB.NET, PHP, SQL Server and MySQL. In his past-time, he listens to polite Carnatic Music. But the big question is that with his current Todolist backlog, does he get some past time?
Follow on   Twitter   LinkedIn

Comments and Discussions

 
QuestionThank You for Posting PinmemberGarry Lowther21-May-13 1:51 
Questionby the way PinmemberMember 1002540317-May-13 9:34 
Questionweb page script generated errors PinmemberMember 1002540317-May-13 9:30 
AnswerRe: web page script generated errors Pinmemberjsc4220-May-13 22:51 
GeneralRe: web page script generated errors PinmemberMember 1002540320-May-13 23:16 
GeneralI appreciate the intention but... Pinmembertom7617-Mar-03 20:40 
GeneralRe: I appreciate the intention but... PinmemberDeepak Kumar Vasudevan17-Mar-03 22:08 
GeneralRe: I appreciate the intention but... Pinmembertom7617-Mar-03 23:03 
GeneralRe: I appreciate the intention but... PinmemberMark F.29-Oct-03 4:24 
Be sure to return 'true' when updating the status bar.
 
window.status = "There were errors getting this page...";
return true;
 
Wink | ;)
 
Mark

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140916.1 | Last Updated 16 May 2013
Article Copyright 2003 by Vasudevan Deepak Kumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid