Advertisement
LaughingMan

Javascript Error Logging with Elmah

May 26th, 2015
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var BaseUrl = window.location.protocol + "//" + window.location.host + "/";
  2. var APIUrl = BaseUrl + "api/";
  3. var errorsAPIUrl = APIUrl + "errors/";
  4.  
  5. Function.prototype.trace = function () {
  6.     var trace = [];
  7.     var current = this;
  8.     while (current) {
  9.         trace.push(current.signature());
  10.         current = current.caller;
  11.     }
  12.     return trace;
  13. };
  14.  
  15. Function.prototype.signature = function () {
  16.     var signature = {
  17.         name: this.getName(),
  18.         params: [],
  19.         toString: function () {
  20.             var params = this.params.length > 0 ?
  21.                 "'" + this.params.join("', '") + "'" : "";
  22.             return this.name + "(" + params + ")";
  23.         }
  24.     };
  25.     if (this.arguments) {
  26.         for (var x = 0; x < this.arguments.length; x++)
  27.             signature.params.push(this.arguments[x]);
  28.     }
  29.     return signature;
  30. };
  31.  
  32. Function.prototype.getName = function () {
  33.     if (this.name)
  34.         return this.name;
  35.     var definition = this.toString().split("\n")[0];
  36.     var exp = /^function ([^\s(]+).+/;
  37.     if (exp.test(definition))
  38.         return definition.split("\n")[0].replace(exp, "$1") || "anonymous";
  39.     return "anonymous";
  40. };
  41.  
  42. window.onerror = function (msg, url, line) {
  43.     if (arguments != null && arguments.callee != null && arguments.callee.trace)
  44.         logError(msg, arguments.callee.trace());
  45. };
  46.  
  47. function logError(ex, stack) {
  48.     if (ex == null) return;
  49.     if (errorsAPIUrl == null) {
  50.         alert('errorsAPIURL must be defined.');
  51.         return;
  52.     }
  53.  
  54.     var url = ex.fileName != null ? ex.fileName : document.location;
  55.     if (stack == null && ex.stack != null)
  56.         stack = ex.stack;
  57.  
  58.     // format output
  59.     var out = ex.message != null ? ex.name + ": " + ex.message : ex;
  60.     out += ": at document path '" + url + "'.";
  61.     if (stack != null) out += "\n  at " + stack.join("\n  at ");
  62.  
  63.     // send error message
  64.     $.ajax({
  65.         type: 'POST',
  66.         url: errorsAPIUrl,
  67.         data: { value: out }
  68.     });
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement