1

I throw an Error using the Error() object in a simplified function like so:

function errorExample() {
  try {
    throw new Error('ConnectionError', 'cannot connect to the internet')
  }
  catch(error) {
    console.log(error
  }
}

I want to be able to access the error name and message from within the catch statement.

According to Mozilla Developer Network I can access them through error.proptotype.name and error.proptotype.message however with the code above I receive undefined.

Is there a way to do this? Thanks.

1
  • See custom error types @ MDN if you want your own name. Commented Feb 23, 2017 at 19:09

3 Answers 3

4

You're misreading the documentation.

Fields on Error.prototype exist on all Error instances. Since error is an instance of the Error constructor, you can write error.message.

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

Comments

2

By default, the name of an error is 'Error', you can override it:

function errorExample() {
  try {
    var e = new Error('cannot connect to the internet');
    e.name = 'ConnectionError';
    throw e;
  }
  catch(error) {
    console.log(error.name);
    console.log(error.message);
  }
}

See: Error.prototype.name

Comments

0

Try this

function errorExample() {
  try {
    throw new Error('ConnectionError', 'cannot connect to the internet');
  }
  catch(error) {
    console.log(error.message);
    console.log(error.name);
  }
}
errorExample() ;

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.