How to catch JavaScript Errors with window.onerror


I’m working on a new responsive website for company that has a fair amount of JavaScript and  that is viewed in lots of different browsers (mobile, tablet, desktop). 
Naturally we want to log our JavaScript exceptions and their stacktraces,  just like we log server-side exceptions. 
It is impossible to test every combination of device and browser so we rely on logging to find the edge cases we miss in our testing.

The way we handle our JavaScript exceptions is to:

 catch the exception.
 collect data about the useragent.

 Save it to our logs by sending an ajax request with the data and the exception information.


$(window).error(function (msg, url, line) 
{   
errorlog(msg.originalEvent.error);
    });



function errorlog(e) { if (typeof (e) == "object") { e.searchurl = location.href; } else if (typeof (e) == "string") { e += "SearchUrl" + location.href; } $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: location.protocol + "//" + location.hostname + "/" + location.pathname + "/errorlog", data: JSON.stringify({ _jsexception: e.stack }), dataType: "json", async: true, success: function (data, textStatus) { if (textStatus == "success") { if (data.hasOwnProperty("d")) { msg = data.d; } else { msg = data; } } }, error: function (data, status, error) { } }); }



Code behind
---------------------------------------------
[System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static void errorlog(object _jsexception)
        {
            string strEmailBody = string.Empty;

            if (_jsexception.GetType().Name == "String")
            {
                strEmailBody += "
Method Name:- Error " + _jsexception as string;

            }
            else
            {
                Dictionary dicErrorAttribute = _jsexception as Dictionary;
                foreach (var _keyandvalue in dicErrorAttribute)
                {
                    if (_keyandvalue.Key == "name")
                    {
                        strEmailBody += "
Method Name:- " + _keyandvalue.Value;

                    }
                    else
                    {
                        strEmailBody += "
" + _keyandvalue.Key + ":- " + _keyandvalue.Value;

                    }
                }
            }
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
            using (con)
            {
                SqlCommand cmd = new SqlCommand("proc_Error", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@Subject", "Error On JavaScript"));
                cmd.Parameters.Add(new SqlParameter("@Body", strEmailBody));
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }

        }


Next PostNewer Posts Previous PostOlder Posts Home