3

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("");
  }

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what code? I already posted my code there's nothing more to it
@fali I think that you are misunderstanding the usage of throw and exceptions, check the answer again.
1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.