Click here to Skip to main content
15,883,749 members
Articles / Web Development / ASP.NET

Log JavaScript Errors

Rate me:
Please Sign up or sign in to vote.
4.05/5 (7 votes)
18 Feb 2008CPOL4 min read 56.5K   235   24   6
Log JavaScript errors in server using AJAX

Introduction

Recently in one of my projects, I'm informed by my QA team that, in some pages they're experiencing crashes, or some pages are not functioning properly after some time.

Our team looked for options where there can be code generating errors. And the feedback I got from the QA team was not helpful to reproduce the error. But there is no doubt that we need 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 it is suppressed.

Background

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

JavaScript
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 number, the filename and the error message.

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

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

But logging into a file on the client side has two issues:

  1. Not supported in browsers other than Internet Explorer (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?

Start adding AJAX code into the function.

Trap Errors and Prepare the Data

JavaScript
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?

JavaScript
if(logJsErrors){ //this line is used for enable or disable Logging. 

The line number, file name and the error message are combined as key value pair.

JavaScript
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

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

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 of 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)  

This writes the data into the file. For extra error handling, we can check if the file is writable.

if (is_writable($filename)) { 

This 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 on 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.

JavaScript
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 delimiter \r\n
$splitcontents = explode($linedelim, $contents);
...
...

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

Summary

  • Written a JavaScript error trapping code, which will suppress the errors
  • Added Ajax Code to send the trapped errors to the server
  • Received 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 too.

History

  • 18th February, 2008: Initial post

License

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


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExternal errors logging Pin
Dumitru Glavan26-May-13 5:10
Dumitru Glavan26-May-13 5:10 
QuestionOnerror is great, but not on iPad, iPhone and Safari Pin
Allan Ebdrup12-Nov-11 20:15
Allan Ebdrup12-Nov-11 20:15 
NewsASP.Net Server Control to help log JavaScript errors Pin
ghmcadams2-Feb-10 8:05
ghmcadams2-Feb-10 8:05 
General[Message Removed] Pin
immetoz4-Oct-08 15:04
immetoz4-Oct-08 15:04 
Generalmake it simple Pin
vicneanschi27-Feb-08 3:49
vicneanschi27-Feb-08 3:49 
GeneralRe: make it simple Pin
Kumar Sundaram27-Feb-08 17:43
Kumar Sundaram27-Feb-08 17:43 

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.