try and catch javascript unexpected identifier - javascript

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!

Related

How to catch JavaScript errors globally without try catch

I have a SPA built with Lightning web components. My basic requirement is to catch any kind of JavaScript exceptions or errors and log them, without having to go to each inner component and wrap every piece of JS code in try catch.
I have tried using window.onerror but I am not getting the proper error message with this, it gives message as "Script error." and line no, col no as 0. Looks like some issue with same origin policy
Can any of you please suggest some other effective way to catch any kind of JavaScript errors globally ?
As far as I know, this is the only way.
Could you please provide the code that you are currently using?
I'll include here the way that i had implemented it.
<script>
window.onerror = function (message, source, lineno, colno, error) {
console.log(`Error: ${error.message} on line: ${lineno} \nfull message: ${error}`)
return true;
};
function triggerError() {
x();
}
triggerError()
</script>
Output: Error: x is not defined on line: 17 full message: ReferenceError: x is not defined

JavaScript: Try/Catch - what am I doing wrong here?

I am wrapping my code into try/catch blocks and I decided to test it out to see how it works.
Below is a simple snippet of code that will generate a Syntax Error - trigge rHandler
try{
$(document).trigge rHandler('fbload');
}catch(e){
alert(e);
}
However I'm not getting the alert! Instead the error is logged in the console as an Unhandled Syntax Error. I was expecting that any error that is generated inside the Try block will automatically be passed down into the Catch section where I can do anything I want with it? Why does this not appear to be working?
try..catch will catch exceptions which occur at runtime. But Syntax errors occur during parsing time itself. So, when the code
$(document).trigge rHandler('fbload');
is encountered, JavaScript tries to parse the expression. But it couldn't. So it is clueless and fails immediately with SyntaxError and that is why it is not caught by the except block.

Chrome: Print exception details to console

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

SSJ - Non-thowable exception

today I had a strange problem in my serverside javascript.
I have a scriptLibrary in which I have some error-handling (try {...} catch(e) {...})
But somethings wrong with the variable "e". On the command e.printStacktrace() (which works useally) I got an exception: Error calling method 'printStackTrace()' on an object of type 'Error [JavaScript Object]'
I have another library, in which I pass the exception to a Java Class which creates a log document in my database, using it thows another exception which says that the variable "e" is not a thowable Exception. Checking that with a print(typeof e) return only "object".
Shouldn't that be a kind of exception on which I can use the standard methods? Do you have any idea what could cause that?
Thanks in advance.
Matthias
The error is not a Java Exception, this is why there is no stack information and no printStackTrace() method available.
Your code throws a Javascript error object. Try e.getMessage() or just a print(e) to get the reason for the failing of your code.

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.

Categories

Resources