本文共 1699 字,大约阅读时间需要 5 分钟。
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 tutorial.
我在教程中对它们进行了分析。
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" } }
翻译自:
转载地址:http://qxmgb.baihongyu.com/