Logging JavaScript errors to a WebService
Victor van Hagen (a collegue of mine at Macaw) has build a nice logging feature into the web application we're building together at the moment. This logging feature takes care of logging client-side JavaScript errors to a special 'Logging' WebService!
This way you're able to monitor the JavaScript errors that occur on the browsers of your clients. Pretty powerful tool to improve your application!
The solution is very simple:
- create a HTML-element that's able to call WebServices (using the free available 'webservice.htc' html component by Microsoft)
- implement the window.onerror, and set this to your own 'logError' javascript function
- inside your 'logError' function, call the logging WebService and send it all error information (and also some information about the client's browser)
- on the 'onresult' event, display a message in the statusbar, informing the user that the error was logged.
Now let's take a look at the code (I've simplified our original code a bit, so it's easier for you to read and understand).
First I'll show you the html page that throws a client-side error, catches it using windows.onerror, and posts it to a logging WebService. Second I'll show you the C# code of the logging WebService (to keep the code simple, the actual logging is left out here).
Note: you can download the webservice.htc code at:
http://msdn.microsoft.com/archive/en-us/samples/internet/behaviors/library/webservice/webservice.htc.
ClientExceptionLogging.htm:
<html>
<head>
<title>Client Exception Logging testpage</title>
</head>
<body>
<div id="logService" style="behavior:url(webservice.htc)"
onresult="window.status='Error logged as LogEnty#' + event.result.value"></div>
<script language="javascript">
function logError(sMsg, sUrl, sLine) {
try {
logService.useService("ClientExceptionLogger.asmx?WSDL", "Logger");
logService.Logger.callService("Log", sMsg, sUrl, sLine,
navigator.appName, navigator.appVersion);
} catch(e) {}
return false; //re-throw error
}
window.onerror = logError;
</script>
<button onclick="blabla.whatever = 3;">Throw an error</button>
</body>
</html>
ClientExceptionLogger.asmx.cs:
namespace ClientExceptionLogging
{
public class ClientExceptionLogger : System.Web.Services.WebService
{
[System.Web.Services.WebMethod]
public int Log(
string msg,
string url,
string sLine,
string navigatorAppName,
string navigatorAppVersion)
{
//TODO: do your logging here (I prefer Log4NET at the moment)
//for testing purposes: return fake LogEntry ID
return new System.Random().Next(int.MaxValue);
}
}
}