处理 JavaScript 中的特定错误(想想异常) [英] Handling specific errors in JavaScript (think exceptions)

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

问题描述

您将如何实现不同类型的错误,以便您能够捕获特定的错误并让其他人冒泡......?

实现此目的的一种方法是修改 Error 对象的原型:

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天全站免登陆