最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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() ;
发布评论

评论列表(0)

  1. 暂无评论