When catching / handling exceptions in JavaScript, how can I determine what the call stack was when the exception occurred? (and also if possible what the line number was)
try
{
// etc...
}
catch (ex)
{
// At this point here I want to be able to print out a detailed exception
// message, complete with call stack, and if possible line numbers.
}
Each browser handles this differently, so there isn't a universal way to do it. This blog post has some good code to dump a stack trace for most supported browsers. I don't think there is a good way to provide the line number.
If you're looking to debug one function in particular, Firebug has a good stack trace function (vis console.trace()).
Have a look at this.
A way to analyse the available information:
try
{
doInit();
} catch(err)
{
var vDebug = "";
for (var prop in err)
{
vDebug += "property: "+ prop+ " value: ["+ err[prop]+ "]\n";
}
vDebug += "toString(): " + " value: [" + err.toString() + "]";
status.rawValue = vDebug;
}
I've discovered that in JavaScript running under IE it is not possible to capture a stack trace at the point that an exception is caught. According to this PDF the only way of getting a stack trace in IE is if you don't handle the exception.
With most errors, you can examine the stack trace, which will include the line and column number of the error location:
try {
throw new Error('foo');
} catch(e) {
console.log(e.message);
console.log(e.stack);
const [, lineno, colno] = e.stack.match(/(\d+):(\d+)/);
console.log('Line:', lineno);
console.log('Column:', colno);
}
This line 13 is correct, because that is the line in the HTML where the error came from in the response from stacksnippets.net:
Note that this will not work for non-errors thrown, like throw null or throw 'foo' (which are not recommended for precisely this reason).
Related
In my MasterPage i'm using the following script
<script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=3.3"></script>
And in my application, i have this peace of JavaScript code
document.getElementById(menu_number).src = "<%=HttpContext.Current.Request.ApplicationPath%>/UI/Common/Images/down-arrow.gif";
I also have the Application_AcquireRequestState method below
public void Application_AcquireRequestState(object sender, EventArgs e)
{
// Get http context from the caller.
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
// Check for encrypted query string
string encryptedQueryString = context.Request.QueryString["request"];
try
{
if (!string.IsNullOrEmpty(encryptedQueryString))
{
// Decrypt query strings
string cryptoKey = System.Web.HttpContext.Current.Session["CryptoKey" + System.Web.HttpContext.Current.Session["UNIQUEKEY"]] == null ? HttpContext.Current.Application["CryptoKey"].ToString() : System.Web.HttpContext.Current.Session["CryptoKey" + System.Web.HttpContext.Current.Session["UNIQUEKEY"]].ToString();
string decryptedQueryString = CryptoQueryStringHandler.DecryptQueryStrings(encryptedQueryString, cryptoKey);
context.Server.Transfer(context.Request.AppRelativeCurrentExecutionFilePath + "?" + decryptedQueryString);
}
}
catch (Exception ex)
{
}
}
When document.getElementById(menu_number).src = "<%=HttpContext.Current.Request.ApplicationPath%>/UI/Common/Images/down-arrow.gif"; is being executed, it throws the below error in IE 11.
JavaScript runtime error: irrationalPath
It also throws an exception in method "Application_AcquireRequestState" but i'm not able to get the exception details. When i put a try -- catch in the method "Application_AcquireRequestState", the exception inner message being returned is
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I'm finding it hard to debug this. The above line of JavaScript executes successfully on the initial page load but throws that error when i'm clicking particular hyperlinks after page load.
What could be the most likely causes of JavaScript error: irrationalPath?
And what does "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack." actually mean?
Any suggestions on how i can effectively troubleshot this?
I have already seen observed that the IrrationalPath exception is defined in the javascript file at http://serverapi.arcgisonline.com/jsapi/arcgis/?v=3.3
The most likely cause of the JavaScript error: irrationalPath error probably has nothing to do with any of the code you posted in the question. It's a dojo error that is usually seen when there's a problem with the dojo loader. It probably has something to do with the paths or pacakges setup in dojoConfig. See here for more info.
The other error you are getting is a .NET error. I can't be certain without seeing more of your code but this Microsoft support article is a good starting place for troubleshooting that erroor
Have you tried to make the HttpContext.Current.Request.ApplicationPath as String in your js code (delimited with two quotes).
js code become :
document.getElementById(menu_number).src = <%="'"+HttpContext.Current.Request.ApplicationPath+"'"%>+"/UI/Common/Images/down-arrow.gif";
I need to get fileName, Message, LineNumber etc from a javascript exception. I tried the following code.
try {
alertt("dddd");
} catch (e) {
console.log("ExceptionType: "+ e.name);
console.log("Message: "+ e.message);
console.log("Line No: "+ e.lineNumber);
}
I got the following result in Mozilla Firefox
ExceptionType: ReferenceError
Message: alertt is not defined
Line No: 4
But the same code gave the following result in Google Chrome, Internet Explorer
ExceptionType: ReferenceError
Message: alertt is not defined
Line No: undefined
It is not giving the Line Number. How to solve this issue? Is there any another method for getting Line number?
I tried e.stack It returns the stack trace as string.
It gave me the following output in Google Chrome
ReferenceError: alertt is not defined
at message (http://localhost/ems-test/js/test.js:4:4)
at HTMLDocument.<anonymous> (http://localhost/ems-test/js/test.js:14:2)
at c (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:26036)
at Object.p.fireWith [as resolveWith] (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:26840)
at Function.x.extend.ready (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:3305)
at HTMLDocument.q (http://localhost/ems-test/js/jquery-1.10.2.min.js:4:717)
and firefox gave this result
message#http://localhost/ems-test/js/test.js:4
#http://localhost/ems-test/js/test.js:14
x.Callbacks/c#http://localhost/ems-test/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith#http://localhost/ems-test/js/jquery-1.10.2.min.js:4
.ready#http://localhost/ems-test/js/jquery-1.10.2.min.js:4
q#http://localhost/ems-test/js/jquery-1.10.2.min.js:4
Both are string type result. Not an object. So it needs to extract the line number from this huge string. But the problem is both result are not same. One shows the line number in first line and another one shows it in second line. So it will be difficult to extract line number from this huge string.
Is there any method to get the stack trace as an object?
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
Hope this might help you.
check on this link: http://www.tutorialspoint.com/cgi-bin/practice.cgi?file=javascript_40
I don't have IE on my machine, so I can't speak for that; but in Chrome, you might be able to get what you need by looking at the e.stack property and parsing it out. You can see the options available to you if you do a console.dir(e) within your catch block.
So right now we have some generic code to report errors either from our code or third party code. Our project is a JQM/Phonegap project for iOS. What is happening is we pretty much always get the same useless error... TypeError: 'undefined' is not a function... with no line number or other helpful information. Is there a way I could change the code to maybe get WHAT is undefined or WHERE it is?
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
//Handle errors not in a jquery event handler
//DebugMessage(errorMSg + " "+ url + " " + lineNumber);
var ex = new Error(errorMsg, url, lineNumber);
HandleError(ex, "window.onerror");
//HandleError sends the error object to
//a webservice to log the error.
return true;
};
Any tips on debugging javascript errors would help as well.
In recent months, browsers have extended the signature of window.onerror to provide more information.
window.onerror = function(msg, file, line, col, error) {
// backwards compat
if (!error) {
error = new Error(msg);
}
// send error to your logger
}
This should give you a lot more information. But there are still things where you need better context. You should check out some third-party tools for this like TrackJS that automatically give you this, plus extra information on how the error occurred.
Disclaimer: I am one of the original authors of TrackJS, so I know a bunch about JavaScript errors :)
Have you heard of Ripple? It is a mobile emulator for Chrome designed for testing PhoneGap applications.
That might help you find your errors before you debug on the devices.
this question is a follow-up to javascript: how to display script errors in a popup alert? where it was explained how to catch regular javascript errors using:
<script type="text/javascript">
window.onerror = function(msg, url, linenumber) {
alert('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
</script>
I tried it and found out that dojo erros like this one:
TypeError: this.canvas is undefined dojo.js (Row 446)
were not reported using this method, which leads me to my question:
How can I report all javascript errors using window.onerror (especially dojo errors)?
It could be Dojo is using proper Error handling methods (i.e. try-catch blocks) which prevents the exception from bubbling up and reaching the window container, on which you have registered the error handler.
If so, there is no way for you to do this. No error is going past the catch block, so no error handler is being called.
As pointed out by the comments, you can also use browser-specific debugging APIs like the Venkman hook and do break-on-error -- a solution that usually only works for privileged code (thanks to #Sam Hanes).
You can also do On(require, 'error', function () {}); to add error handling on DOJO's asynchronous script loader -- another point mentioned in the comments by #buggedcom
you can write code like this:
var goErrHandler=window.onerror;
goErrHandler= function(msg, url, linenumber) {
console.log('Error message: '+msg+'\nURL: '+url+'\nLine Number: '+linenumber);
return true;
}
goErrHandler();
so in console you'll see some thing like this :
Error message: undefined
URL: undefined
Line Number: undefined
The better solution is to use try/catch, e.g.
try{
if(a=='a'){
}
}catch(e){
alert(e);
//or send to server
new Image().src='errorReport.php?e='+e;
}
Google Plus seems to use this.
I'm looking to log unhandled javascript exceptions. Is there an event that fires when an exception isn't caught? I'm looking to catch the exceptions before they cause javascript errors in the browser, but I'd rather not run my entire application inside of a try/catch. Any help would be appreciated. Thanks!
Update:
tvanfosson pointed out onerror as a possibility. It is not part of a spec and is only available in IE or Gecko based browsers.
For more information - http://books.google.com/books?id=tKszhx-XkzYC&pg=PA386&lpg=PA386&dq=safari+onerror+javascript&source=web&ots=gQaGbpUnjG&sig=iBCtOQs0aH_EAzSbWlGa9v5flyo#PPA387,M1
OnError Support Table - http://www.quirksmode.org/dom/events/error.html
Mozilla's documentation - https://developer.mozilla.org/en/DOM/window.onerror
WebKit Bug Report - https://bugs.webkit.org/show_bug.cgi?id=8519
Check out this Fiddle:
http://jsfiddle.net/xYsRA/1/
window.onerror = function (msg, url, line) {
console.log("Caught[via window.onerror]: '" + msg + "' from " + url + ":" + line);
return true; // same as preventDefault
};
window.addEventListener('error', function (evt) {
console.log("Caught[via 'error' event]: '" + evt.message + "' from " + evt.filename + ":" + evt.lineno);
console.log(evt); // has srcElement / target / etc
evt.preventDefault();
});
throw new Error("Hewwo world. I crash you!!!");
throw new Error("Hewwo world. I can only crash you once... :(");
Which prints:
Caught[via window.onerror]: 'Uncaught Error: Hewwo world. I crash you!!!' from http://fiddle.jshell.net/xYsRA/1/show/:32 fiddle.jshell.net:21
Caught[via 'error' event]: 'Uncaught Error: Hewwo world. I crash you!!!' from http://fiddle.jshell.net/xYsRA/1/show/:32 fiddle.jshell.net:26
ErrorEvent {lineno: 32, filename: "http://fiddle.jshell.net/xYsRA/1/show/", message: "Uncaught Error: Hewwo world. I crash you!!!", clipboardData: undefined, cancelBubble: falseā¦}
fiddle.jshell.net:27\
Notes:
If you remove the "return true" / "evt.preventDefault()" lines, then after the error is logged, it will print on the JS console in the normal way.
Contrary to statements made above, window.onerror worked in all the browsers I tested. However, the addEventListener method is probably better anyways and provides richer semantics.
Try using an onerror handler. Docs from MDN. This will allow you to do something when an error is detected, but probably won't let you continue in a graceful way that a try/catch block would. Be aware that are undoubtedly differences between browsers in how this is handled.