I am trying to customize error message for exception throw in javascript.
So far my attempts have been failed.
I am trying this but its not working
function abc(sender, args) {
alert("ex2");
throw ("error new");
alert("");
}
You need to throw and object (with name and message properties) instead of a string to generate a custom exception:
function abc(sender, args) {
alert('ex2');
throw {
name: 'YourErrorName',
message: 'YourErrorMessage'
};
alert('');
}
Here is a sample of how to raise the event and catch the exception which contains your name and message values:
function triggerError(){
throw {
name: 'YourErrorName',
message: 'YourErrorMessage'
};
};
(function cathError(){
try {
triggerError();
}
catch(e){
console.log(e.message);
console.log(e.name);
}
}());
Check out this codepen to see it working.
I've had good luck with this simple code:
throw new Error("Something terrible has happened");
When you simply throw a string, you lose functionality such as the error stack. Somewhere up the call stack you might want to do something like:
catch(err) {
console.log(err.stack);
alert(err.message);
}