Chrome: Print exception details to console - javascript

How do I print the stack trace of an Exception in the chrome devtools from my code?
I tried the following:
function doSomething() {
undefined(); // This throws an exception
}
try {
doSomething();
} catch (e) {
console.error("Exception thrown", e);
}
But this yields the following result:
Exception thrown TypeError {}
And if I expand the arrow next to it, it points me to the line where the console.error() call was made, so I don't get to see where the original error actually happened.
What would be the best way to include the original error information (including message and complete stack trace to the exact location where the error happened) in the console output?

Object Error has a property stack. Print it out.
console.error("Exception thrown", e.stack);
Please note that stack property is not standardized and it is only used by V8 based browsers + IE. Firefox uses different convention.

You can output the error as object
console.error("%O", e)
Using string substitutions

Related

How to pass native ReferenceError object stack to console in a JavaScript try catch?

In JavaScript, when using a try catch, how can I get the native Chrome ReferenceError object to the console as it would normally be logged? I can get close by using the Error object's stack property, but it logs the errors differently:
try {
bet you can't run this you dumb computer;
}
catch(error) {
console.log(error.stack);
}
When running the above, I get the following in the console:
While this is slightly helpful, clicking on the line number takes me to the console.log(error.stack) line in the code, not the error.
Without the try catch, the error looks like this:
and clicking on the line number will take me exactly to where the original error occurred. So how can I get this native Chrome error object to pass to the catch and then log to the console so that I can navigate to the original error and line that was thrown as it would normally be without the try catch in place?
I believe it'll work with the error method from the console object:
try {
bet you can not run this you dumb computer;
}
catch(error) {
console.error(error);
}
Hope this helps!

Checking if specific console error occurred/exists with javascript

I would like to check if a certain console error has occurred using javascript, and alert() myself if it has.
The error will look like this:
00:00:34:0359 TimeEvent.COMPLETE
(anonymous function) # VM17617:1
And the algorithm will look something like this:
function checkError(console) {
if(console.error === "TimeEvent.COMPLETE") {
alert("The error is present");
}
}
I'm not very familiar with the console, and haven't gotten much further with Google research. Can somebody point me in the right direction?
I ultimately solved my question by following this blog post on taking over the console with javascript.
Here is my final code:
var original = window.console
window.console = {
error: function(){
//Gets text from error message.
errorText = arguments['0'];
if (errorText.includes('TimeEvent.COMPLETE')) {
//DO STUFF HERE
}
original.error.apply(original, arguments)
}
}
You didn't provide the whole picture about how and when the console is getting the error. If you raise the error yourself, or if you are able to catch it inside a try catch, that would be the best place to intercept those errors.
However, if you have no control about how those error are raised, you should try to intercept your console's error calls. I never tried it myself but this SO answer explains how to intercept the console's log calls. Knowing that the console usually have a function named error that is similar to the log function, I'm sure you could apply the same logic to intercept the errors sent to the console.
If you are using chrome, you may refer to the console documentation for more details about the error function. I'm not sure if there's a standard butInternet Explorer and Firefox also has support for console error function.

try and catch javascript unexpected identifier

i'm tryin to identify the error i get in a javascrip function in my webpage, so i added
function guardarMisDatos() throws Exception {
try{
...
} catch (Exception e){
alert("error: ", e);
}
but when i open the page, the chrome web console gives me error at
function guardarMisDatos() throws Exception {
and the error type is "Uncaught syntaxerror: unexpected identifier"
where is the error? is it a correct way to check way the function is not fired on the first click?
It is JavaScript not Java. Lose the throws Exception!
Your code looks a lot like Java, not javaScript. The syntax for try/catch in javaScript goes like this:
try {
// do stuff
} catch (e) {
// something bad happened
}
Notice there is no throws and no type on e (since javascript is loosely typed)
Remove "throws Exception" and the catch reference to "Exception". To know what kind of exception it is, look at the e.name property, it'll be one of six things:
EvalError - An error in the eval() function has occurred.
RangeError - ut of range number value has occurred.
ReferenceError - An illegal reference has occurred.
SyntaxError - A syntax error within code inside the eval() function has occurred. All other syntax errors are not caught by try/catch/finally, and will trigger the default browser error message associated with the error. To catch actual syntax errors, you may use the onerror event.
TypeError - An error in the expected variable type has occurred.
URIError - An error when encoding or decoding the URI has occurred (ie: when calling encodeURI()).
These aren't constants, they're the actual string, as in if (e.name.toString()=="TypeError") There are a lot of other good things on the error object too, read more at http://www.javascriptkit.com/javatutors/trycatch2.shtml
Remove the throws Exception from your function definition. You do not need this in JavaScript. Besides that, why would your function ever throw an exception - you already catch it!

How to create, design and throw built-in Error objects

UPDATE
[Rewriting question to focus on the problem I am trying to understand.]
Is there a means in JavaScript to throw Exceptions that notify the line number where the problem occurs? Similar to C#'s debugger, if an error is thrown on line 50 then I will be taken to line 50.
For example, according to MDN EvalError represents an error with eval(). So, let's say I have a function that uses eval(). I want to use a specific error that is representative of the problem at hand, EvalError:
//As written here the error implies there is a problem on this line. See Firebug console window
var evalErra = new EvalError('required element missing from evaluation');
var stringFunc = "a=2;y=3;document.write(x*y);";
EvalString(stringFunc);
function EvalString(stringObject) {
//Some arbitrary check, for arguments sake let's say checking for 'x' makes this eval() valid.
if(stringObject.indexOf('x') !== -1) {
throw evalErra;
//throw 'required element missing from evaluation';//This way offers no line number
}
eval(stringFunc);//The problem really lies in the context of this function.
}
If I'm going about this all wrong, then please tell me how I should approach these kinds of issues.
When you throw an error, execution of the current code will stop and JS will work its way back up the execution tree until it finds a catch () which handles the particular type of error being thrown, or gets all the way up to the top of the tree, causing an "unhandled exception" error: You threw an error, and nothing caught it, and now someone's window got broken.
try {
if (true) {
throw 'yup'
}
} catch (e) { // catches all errors
... handle the error
}
When doing error handling you want to do the following
throw new Error("message");
Then if you ever handle this error look at err.stack (firefox/opera/chrome) or err.line (Safari) or err.IE_Y_U_NO_SHOW_ME_ERROR_LINE_NUMBER (IE) to find the line number.
If you want you can subclass Error.

Throwing errors in Javascript with error object relevancy

This is pretty much IE related because IE is the environment I'm using to test this, but I want to know if you can affect the relevancy of the error object properties when you throw an error. Consider the following javascript:
function MyClass (Arg1, Arg2) // Line 5 of my.js
{
if (typeof Arg1 != "string")
throw new Error("Invalid argument passed for MyClass");
// Do some other stuff here
}
Further down your code you have
var myvar = new MyClass(100, "Hello"); // Line 3201 of my.js
So the above would throw an error, but the error reported in the debugging information would show the error being thrown at line 9 of my.js instead of line 3201. Is this something you can change using standard methods?
What you are actually looking for is a stack trace for the error. There are no standards for this but most browsers do provide some means of discovery. Doing a quick search comes up with this js stack trace example.
In firefox you can use the stack property when you catch the error. In other browsers you can use the message property.
Have a look at this link on how to catch the stacktrace.

Categories

Resources