简体   繁体   中英

Exception logging in JavaScript, capture stack trace

I used https://github.com/eriwen/javascript-stacktrace to capture stack trace when exception happens.

In some cases the logged information looks very strange, for example the user uses IE9 and the logged message is at {anonymous}()
 at printStackTrace()
 at {anonymous}(#object,"error","")
 at {anonymous}(#object,[#object...""])
 at d(12031,"",#object,"")
 at {anonymous}() at {anonymous}()
 at printStackTrace()
 at {anonymous}(#object,"error","")
 at {anonymous}(#object,[#object...""])
 at d(12031,"",#object,"")
 at {anonymous}() at {anonymous}()
 at printStackTrace()
 at {anonymous}(#object,"error","")
 at {anonymous}(#object,[#object...""])
 at d(12031,"",#object,"")
 at {anonymous}() .

In my code I have quite some jQuery event handling code

$(document).ready(function () {
    $('#reset').bind('click', reset);
}

function reset(e){
    $.ajax({
        type: 'POST',
        url: '/my/url',
        dataType: "json",
        success: function (result) {
            // do something useful
        },
        error: function (request, error) {
            // log to server side.
            logError(error, printStackTrace());
        }
    });
}

I think in this case the captured stack trace just look like anonymous objects.

Is there a better way I can capture stack trace in a more readable way?

How about try catch block take a look at the link

<script>
var txt="";
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " + err.message + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }
}
</script>

http://www.w3schools.com/js/js_errors.asp

Each function in Javascript used to have a caller property, but due to security restrictions you cannot count on it anymore.

Even if you could, there's not much you can do about the anonymous functions, as they simply don't have a name. you could take the string with the stack trace and make it a little prettier:

function prettyTrace(stackTrace) {
    if (!stackTrace || stackTrace === "")
        return "";

    return stackTrace.replace(/\&[^;]+\;/, "");
}

I think I know the reason, according to http://kangax.github.com/nfe/ function expressions is the only way to get a truly robust stack inspection .

So in the coding, we have to consider how to create function in order to allow debugger to capture the name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM