jQuery ajax error logging on the server with log4net

This post is based on Toby Gundry’s post on the same technique, but adapted for logging jQuery ajax errors (although I added a few extra things too).

In your Javascript:

    $(document).on({
        ajaxError: function (event, jqXHR, ajaxSettings) {
            var err = “Location: " + document.location.href + “; “;
   
            if (jqXHR)
            {
                err += “Status: " + jqXHR.status + “; “;
                err += “Text: " + jqXHR.statusText + “; “;
            }
   
            if (jqXHR.responseJSON) {
                err += “Message: " + jqXHR.responseJSON.Message + “; “;
                err += “Stack Trace: " + jqXHR.responseJSON.StackTrace + “; “;
            }
   
            if (ajaxSettings) {
                err += “Data Sent: " + ajaxSettings.data + “; “;
                err += “URL: " + ajaxSettings.url + “; “;
            }
   
            var message = btoa(err);
            var log = new Image();
            log.src = “/JSLogger.ashx?error=” + message;
   
            //display some kind of friendly error message to the user
        }
    });

I used the btoa function for base64-encoding the content, but it’s quite possibly unnecessary.  Anyway, make a JSLogger handler, something like this:

    public class JSLogger : IHttpHandler
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(JSLogger));

        public void ProcessRequest(HttpContext context)
        {
            string encodedError = context.Request.QueryString[“error”];
            byte[] bytes = Convert.FromBase64String(input);
            string error = Encoding.ASCII.GetString(bytes); //using Unicode seems to have weird effects

            try
            {
                string name = “Username: " + context.User.Identity.Name;
                error += name;
            }
            catch(Exception e){} //in case the username isn’t available
           
            Log.Error(error);
        }

        //IHttpHandler boilerplate omitted
    }

Let me know if you have any ideas for improvement!