博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript中的自定义错误
阅读量:2507 次
发布时间:2019-05-11

本文共 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/

你可能感兴趣的文章
代码示例_进程
查看>>
Java中关键词之this,super的使用
查看>>
人工智能暑期课程实践项目——智能家居控制(一)
查看>>
前端数据可视化插件(二)图谱
查看>>
kafka web端管理工具 kafka-manager【转发】
查看>>
获取控制台窗口句柄GetConsoleWindow
查看>>
Linux下Qt+CUDA调试并运行
查看>>
51nod 1197 字符串的数量 V2(矩阵快速幂+数论?)
查看>>
OKMX6Q在ltib生成的rootfs基础上制作带QT库的根文件系统
查看>>
zabbix
查看>>
多线程基础
查看>>
完美解决 error C2220: warning treated as error - no ‘object’ file generated
查看>>
使用SQL*PLUS,构建完美excel或html输出
查看>>
SQL Server数据库笔记
查看>>
X-Forwarded-For伪造及防御
查看>>
android系统平台显示驱动开发简要:LCD驱动调试篇『四』
查看>>
Android 高仿微信头像截取 打造不一样的自定义控件
查看>>
Jenkins的初级应用(1)-Publish Over SSH
查看>>
利用正则表达式群发定制邮件
查看>>
【原】RDD专题
查看>>