admin管理员组

文章数量:1415111

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.

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.

Share Improve this question asked Feb 23, 2017 at 19:06 Pav SidhuPav Sidhu 6,96419 gold badges61 silver badges112 bronze badges 1
  • See custom error types @ MDN if you want your own name. – Alex K. Commented Feb 23, 2017 at 19:09
Add a ment  | 

3 Answers 3

Reset to default 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.

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

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

本文标签: Javascript retrieving error name and message from Error() objectStack Overflow