Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » JavaScript » Log Javascript Errors using AJAX

Log Javascript Errors using AJAX

Log the JavaScript Errors that are generated in the client, using AJAX at server side. ASP, JSP, PHP or any server side scripting can be used.

Page Views : 2499
Downloads : 48
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
jslogs.zip | jslogs.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction

Recently in one of my projects, experienced browser crashes, or some pages not functioning properly after sometime.

I looked for options where there can be a code generating errors. And the feedback I got, was not helpful to reproduce the error. But there is no doubt to look for areas only in JavaScript coding, and not other than JavaScript coding.

Normally while releasing a project, what I would do is, just escape/bypass the JavaScript errors. That means, whenever there is a JavaScript error, it will not be reported to the user and they are suppressed.

Background

Following is the function, we can normally use to suppress the JavaScript errors.

            
var isDebugging = true;

function ErrorSetting(msg, file_loc, line_no) {
    var e_msg=msg;
    var e_file=file_loc;
    var e_line=line_no;
    var error_d = "Error in file: " + file_loc +
                          "\nline number:" + line_no +
                           "\nMessage:" + msg;
    if(isDebugging)
        alert("Error Found !!!\n--------------\n"+error_d);

     return true;
}
window.onerror = ErrorSetting;
         

window.onerror = ErrorSetting; this line will call the 'ErrorSetting' function, whenever there is a JavaScript error. And the function will return true. So the user will not get JavaScript
error notifications and won't be annoyed.

While in the development stage the variable 'isDebugging' is set as true, and we can get
the JavaScript alerts, notifying the error with the line no, the filename and the error message.

The above method is commonly used by many web developers. This is the same I were using in my previous projects.

But in this particular project, I have to get error messages in the real-time when they are using, immediately in my mind I got an idea of logging the errors. (Later I searched thru the web and there are many developers have done it like this!? :( )

But logging into a file in the client side is having two issues.
1. Not supported in browsers other than IE (Only using ActiveX Objects)
2. The files will be stored in the client side not in server.

So I used AJAX, to silently send the JavaScript errors to the server, where the errors
Will be, written in a flat file. And later we can view the file for error logs.

What next ?

Started adding AJAX code into the function.

Trap Errors and Prepare the Data

var isDebugging = false;
var logJsErrors = true;

function ErrorSetting(msg, file_loc, line_no) {
    var e_msg=msg;
    var e_file=file_loc;
    var e_line=line_no;
    var   error_d = "Error in file: " + file_loc +"\nline number:" 
            + line_no +
                        "\nMessage:" + msg;

    if(logJsErrors){
        theData = "file="+file_loc+"&line="+line_no+"&err="+msg;
        ajaxCtrl(
            function(){
                return true;
            },"ajxerrorLogger.php",theData
        );
    }

    if(isDebugging)
        alert("Error Found !!!\n--------------\n"+error_d);

     return true;
}
window.onerror = ErrorSetting;

       

What the above function does?
if(logJsErrors){ //this line is used for enable or disable Logging.

The line no, file name and the error message are combined as key value pair.theData = "file="+file_loc+"&line="+line_no+"&err="+msg;

Now the data is ready, we can now call the AJAX function that will send the data to the server.

Send Data to Server

ajaxCtrl(    
    function(){
        return true;
    },"ajxerrorLogger.php",theData
); 

The remote file is "ajxerrorLogger.php".

I've used PHP for this. Instead you can use ASP, JSP also.

This is used to receive the data sent from the JavaScript error handling function. That's it. Our JavaScript errors are now sent to the server silently. What Next? In the server side, we have to code the "ajxerrorLogger.php"

Receive Data and Write into a File

if($_POST && $_POST['file']!=''){
    $filename = "./errlogs.txt";
    $fh = fopen($filename,"a+");

    //the content is in the form

    //Date    File    LineNo    Error Message
    //(tab delimited)
    $fcontent = date("d/m/Y h:i:s", mktime())."\t".
    $_POST['file']."\t".$_POST['line']."\t".$_POST['err']."\r\n";
    if (is_writable($filename)) {
        if (fwrite($fh, $fcontent) === FALSE) {
        }
        fclose($fh);
    }

}

$fh = fopen($filename,"a+"); 
  

Opens the File errlogs.txt in append mode. So the new errors will be added into the file without overwriting it.

We are going to save the data ( js errors ) as tab delimited. For the sake reference we can store the date and time also.

$fcontent=date("d/m/Yh:i:s", mktime()). "\t".
$_POST['file']. "\t" .$_POST['line'].
                "\t".$_POST['err']."\r\n"; 

Now the data is ready to be written into the file.

fwrite($fh, $fcontent)  

writes the data into the file. For extra error handling we can check,

if the file is writable.

          if (is_writable($filename)) { 

Will check and return TRUE if the file is writable. Then we can write the data. That's it. We
have successfully logged our JavaScript errors in the server silently and we can see the errors
that are occurring in the client side, while they are using the site.

See the Errors real-time?

How? We have to add a small, separate PHP file to view the logs
we have generated above. The script will read the file and show
the contents.

if (file_exists($filename) && is_readable($filename)) { //if exists and readable

    $contents = fread($fh,filesize ($filename)); //read the whole file
    fclose($fh); //and close
} 
//now split the file content into lines
//using the line delimeter \r\n

$splitcontents = explode($linedelim, $contents);
...
...

Add some lines to show each line read from the file. We are done.

Summary

  • We have written a JavaScript error trapping code, which will suppress the errors
  • Added Ajax Code To send the trapped errors to the server
  • Receive the data and store into a flat file using PHP
  • Added a small script to see the logged JavaScript errors remotely.

Improvements

  • The script can be further improved by adding capability to send the logs in mail to the administrator.
  • Instead of writing into a flat file, we can store into a database.
  • The same thing can be done using PHP as well as ASP, JSP also.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Kumar S
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.