Reputation: 1817
I am trying to understand the result of a challenge in my course and I am stuck to pass, as the result is not matching with what they are expecting. The challenge tasks are:
myError
myErrorName
myErrorMessage
Write a finally block that checks to see if myError
exists.(myErrorName: myErrorMessage)
The approach I have is as follow:
try{
myVar();
}
catch(err){
var myError = err;
var myErrorName = err.name;
var myErrorMessage = err.message;
}
finally{
if(myError == err){
var result = "There was an error (myErrorName:myErrorMessage)";
}else{
console.log("No error ocurred");
}
}
Upvotes: 1
Views: 879
Reputation: 543
Check this It will work
try{
console.log(myVar);
}
catch(err){
var myError = err;
var myErrorName = err.name;
var myErrorMessage = err.message;
}
finally{
if(myError){
var result = "There was an error ("+ myErrorName+": "+myErrorMessage+")";
}else{
result = "No error ocurred";
}
}
Upvotes: 0
Reputation: 1074088
There are two primary problems with that code:
You have a typo: var myErro = err;
is missing the r
on the end of myErro
.
You're trying to use err
in the finally
block, but it's only in scope in the catch
block.
...and then a few more that don't match what it seems like the assignment is telling you to do
You're not doing #1, you're doing something else which coincidentally also tries to use myVar
You don't have any code implementing #6.
Your code assigning result
when there's an error is putting myErrorName
and myErrorMessage
literally in the string, rather than using the values of those variables.
Your message for when no errors have occurred is not the same as the message they told you to use, it has slight differences (including a typo). Programming is at least partially about attention to detail. :-)
You don't need if (myError == err)
, just if (myError)
will do:
try{
myVar();
}
catch(err){
var myError = err;
var myErrorName = err.name;
var myErrorMessage = err.message;
}
finally{
if(myError){
var result = "There was an error (myErrorName:myErrorMessage)";
console.log(result);
}else{
console.log("No error ocurred");
}
}
(I added a console.log
so we'd see the error case.)
I've only addressed #1 and #2 in the above, the rest are left as an exercise for you to complete. :-)
I should note that I wouldn't write it that way. Declaring a variable in the catch
block that you use in the finally
block does work, with var
(because var
is not block-scoped and is hoisted), but it's misleading to people trying to maintain the code. If you're going to use a variable in both of those blocks, move the declaration outside the blocks for clarity.
Upvotes: 7