Javascript retrieving error name and message from Error() object - Stack Overflow

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745211630a4616876.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信