Pav Sidhu
Pav Sidhu

Reputation: 6944

Javascript retrieving error name and message from Error() object

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.

Upvotes: 1

Views: 4403

Answers (3)

iLearn
iLearn

Reputation: 1179

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

Upvotes: 0

Austin France
Austin France

Reputation: 2501

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

Upvotes: 2

SLaks
SLaks

Reputation: 887453

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.

Upvotes: 4

Related Questions