Click here to Skip to main content
13,350,506 members (56,979 online)
Click here to Skip to main content
Add your own
alternative version


35 bookmarked
Posted 29 Dec 2011

How to Log Javascript Errors in C#

, 29 Dec 2011
Rate this:
Please Sign up or sign in to vote.
Logging client side JavaScript errors to the server.

This code shows how to handle a JavaScript error by posting the details back to the server to be logged. This code can be wired up to use any logging system.

The errors.js file establishes a handler for window.onerror to call the handleError function. The handleError function creates a web request (using the createHttpRequest function in httpRequests.js) and posts the error details back to LogJavascriptError.aspx. The LogJavascriptError.aspx file then logs the details to the file.


var applicationPath = '';

function handleError(msg, srcUrl, line){

    var receiveReq = createHttpRequest();

    var url = applicationPath + '/Admin/LogJavascriptError.aspx';

    var data  = "ErrorData=" + msg + "&SourcePage=" + srcUrl + "&Line=" + line;"POST", url, true);

    receiveReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    receiveReq.setRequestHeader("Content-length", data.length);
    receiveReq.setRequestHeader("Connection", "close");




function createHttpRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest(); //Not IE
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP"); //IE
    } else {
        alert("Your browser doesn't support the XmlHttpRequest object.  Please upgrade to Firefox.");


string errorData = Request.Form["ErrorData"];
string sourcePage = Request.Form["SourcePage"];
string line = Request.Form["Line"];

string full = "Javascript error: " + errorData + Environment.NewLine + 
              "Location: " + sourcePage + ", line " + line;




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


About the Author

Australia Australia
Founder of

You may also be interested in...

Comments and Discussions

QuestionBe careful here Pin
tmbgfan29-Dec-11 6:54
membertmbgfan29-Dec-11 6:54 
AnswerRe: Be careful here Pin
SoftwareMonkeys29-Dec-11 11:38
memberSoftwareMonkeys29-Dec-11 11:38 
GeneralRe: Be careful here Pin
baskinhu3-Jan-12 5:06
memberbaskinhu3-Jan-12 5:06 
GeneralRe: Be careful here Pin
SoftwareMonkeys3-Jan-12 12:32
memberSoftwareMonkeys3-Jan-12 12:32 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 29 Dec 2011
Article Copyright 2011 by SoftwareMonkeys
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid