处理JavaScript中的特定错误(认为例外) [英] Handling specific errors in JavaScript (think exceptions)

查看:105
本文介绍了处理JavaScript中的特定错误(认为例外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何实施不同类型的错误,因此您可以抓住具体的错误,让其他人冒泡。



实现这一点的一种方法是修改错误对象的原型:

How would you implement different types of errors, so you'd be able to catch specific ones and let others bubble up..?

One way to achieve this is to modify the prototype of the Error object:

Error.prototype.sender = "";


function throwSpecificError()
{
    var e = new Error();

    e.sender = "specific";

    throw e;
}

捕捉具体错误:

try
{
    throwSpecificError();
}

catch (e)
{
    if (e.sender !== "specific") throw e;

    // handle specific error
}



你有没有其他选择?


Have you guys got any alternatives?

推荐答案

要创建自定义异常,可以从Error对象继承:

To create custom exceptions, you can inherit from the Error object:

function SpecificError () {

}

SpecificError.prototype = new Error();

// ...
try {
  throw new SpecificError;
} catch (e) {
  if (e instanceof SpecificError) {
   // specific error
  } else {
    throw e; // let others bubble up
  }
}

一个简约的方法,没有继承自Error,可能会抛出一个简单的对象,其名称和消息属性:

A minimalistic approach, without inheriting from Error, could be throwing a simple object having a name and a message properties:

function throwSpecificError() {
  throw {
    name: 'SpecificError',
    message: 'SpecificError occurred!'
  };
}


// ...
try {
  throwSpecificError();
} catch (e) {
  if (e.name == 'SpecificError') {
   // specific error
  } else {
    throw e; // let others bubble up
  }
}

这篇关于处理JavaScript中的特定错误(认为例外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆