Click here to Skip to main content
15,880,405 members
Articles / Programming Languages / Javascript

Graceful Handling Of JavaScript Errors

Rate me:
Please Sign up or sign in to vote.
3.19/5 (12 votes)
16 May 2013CPOL3 min read 71.8K   32   9
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:

    JavaScript
    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.  
JavaScript
<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)


Written By
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?

Comments and Discussions

 
QuestionThank You for Posting Pin
Garry Lowther21-May-13 1:51
Garry Lowther21-May-13 1:51 
Questionby the way Pin
Member 1002540317-May-13 9:34
Member 1002540317-May-13 9:34 
Questionweb page script generated errors Pin
Member 1002540317-May-13 9:30
Member 1002540317-May-13 9:30 
AnswerRe: web page script generated errors Pin
jsc4220-May-13 22:51
professionaljsc4220-May-13 22:51 
Excluding very simple trivial unuseful programs, it is impossible to write 100% perfect code. Even if your code works in one environment (browser in this context), that does not guarantee that it will work in some future environment or some ancient environment or some other unpredictable scenario. [For example, when I started with JavaScript, to update the page you tested for document.all (for IE4 and lower) or document.layers (for NN4 or lower); but very few people these days use anything other than document.getElementById].

You should test to destruction; but that does not ensure that the code is perfect. You must include error handling. The maxim is "Expect the unexpected".
GeneralRe: web page script generated errors Pin
Member 1002540320-May-13 23:16
Member 1002540320-May-13 23:16 
GeneralI appreciate the intention but... Pin
tom7617-Mar-03 20:40
tom7617-Mar-03 20:40 
GeneralRe: I appreciate the intention but... Pin
Vasudevan Deepak Kumar17-Mar-03 22:08
Vasudevan Deepak Kumar17-Mar-03 22:08 
GeneralRe: I appreciate the intention but... Pin
tom7617-Mar-03 23:03
tom7617-Mar-03 23:03 
GeneralRe: I appreciate the intention but... Pin
Mark F.29-Oct-03 4:24
Mark F.29-Oct-03 4:24 

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

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