JavaScript中的自定义错误

JavaScript gives us a set of 8 error objects, which are raised in a try/catch expression depending on the error type. They are:

JavaScript为我们提供了8个错误对象的集合,这些对象会根据错误类型在try / catch表达式中引发。 他们是:

  • Error

    Error

  • EvalError

    EvalError

  • RangeError

    RangeError

  • ReferenceError

    ReferenceError

  • SyntaxError

    SyntaxError

  • TypeError

    TypeError

  • URIError

    URIError

I analyzed them all in the JavaScript errors tutorial.

我在JavaScript错误教程中对它们进行了分析。

Here I want to explain how to create your own custom errors by extending the base Error class:

在这里,我想解释如何通过扩展基本Error类来创建自己的自定义错误:

class OutOfFuelError extends Error {}

class FlatTireError extends Error {}

Custom errors allow you to behave differently based on the specific error type, without resorting to use error messages to understand the kind of error.

自定义错误使您可以根据特定的错误类型采取不同的行为,而无需借助错误消息来了解错误的类型。

try {
  //some code
} catch (err) {
  if (err instanceof OutOfFuelError) {
    //handle error
  } else if (err instanceof FlatTireError) {
    //handle error
  }
}

Before you can do so, of course the error must be explicitly thrown in your code:

当然,在执行此操作之前,必须在代码中明确抛出该错误:

try {
  const car = new Car() //imagine we have a Car object

  if (!car.fuel) {
    throw new OutOfFuelError('No fuel!')
  }
  if (car.flatTire) {
    throw new FlatTireError('Flat tire!')
  }
} catch (err) {
  if (err instanceof OutOfFuelError) {
    //handle error
  } else if (err instanceof FlatTireError) {
    //handle error
  }
}

During the error creation you can also customize anything related to the class, even customizing the parameters received by the constructor if you need:

在错误创建期间,您还可以自定义与类相关的任何内容,甚至在需要时还可以自定义构造函数收到的参数:

class OutOfFuelError extends Error {
  constructor(message) {
    super(message)
    this.name = "OutOfFuelError"
  } 
}

翻译自: https://flaviocopes.com/javascript-custom-errors/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值