如何在switch语句中使用instanceof

编程入门 行业动态 更新时间:2024-10-28 20:17:42
本文介绍了如何在switch语句中使用instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用自定义错误( es6-error ),允许我处理基于他们的课程就像这样:

I use custom errors (es6-error) allowing me to handle errors based on their class like so:

import { DatabaseEntryNotFoundError, NotAllowedError } from 'customError'; function fooRoute(req, res) { doSomethingAsync() .then(() => { // on resolve / success return res.send(200); }) .catch((error) => { // on reject / failure if (error instanceof DatabaseEntryNotFoundError) { return res.send(404); } else if (error instanceof NotAllowedError) { return res.send(400); } log('Failed to do something async with an unspecified error: ', error); return res.send(500); }; }

现在我宁愿为这种类型的流程使用一个开关,导致如下:

Now I'd rather use a switch for this type of flow, resulting in something like:

import { DatabaseEntryNotFoundError, NotAllowedError } from 'customError'; function fooRoute(req, res) { doSomethingAsync() .then(() => { // on resolve / success return res.send(200); }) .catch((error) => { // on reject / failure switch (error instanceof) { case NotAllowedError: return res.send(400); case DatabaseEntryNotFoundError: return res.send(404); default: log('Failed to do something async with an unspecified error: ', error); return res.send(500); } }); }

instanceof 不起作用。所以后者失败。

instanceof doesn't work like that however. So the latter fails.

有没有办法在switch语句中检查其类的实例?

Is there any way to check an instance for its class in a switch statement?

推荐答案

一个好的选择是使用构造函数 属性对象:

A good option is to use the constructor property of the object:

// on reject / failure switch (error.constructor) { case NotAllowedError: return res.send(400); case DatabaseEntryNotFoundError: return res.send(404); default: log('Failed to do something async with an unspecified error: ', error); return res.send(500); }

请注意,构造函数必须与创建对象的对象完全匹配(假设错误是 NotAllowedError 和 NotAllowedError 是的子类):

Notice that the constructor must match exactly with the one that object was created (suppose error is an instance of NotAllowedError and NotAllowedError is a subclass of Error):

  • error.constructor === NotAllowedError 是 true
  • error.constructor ===错误是 false
  • error.constructor === NotAllowedError is true
  • error.constructor === Error is false

这与 instanceof 有所不同,它也可以匹配超级类:

This makes a difference from instanceof, which can match also the super class:

  • 错误实例NotAllowedError 是 true
  • error instanceof错误是 true
  • error instanceof NotAllowedError is true
  • error instanceof Error is true

检查这个有趣的帖子关于构造函数财产。

更多推荐

如何在switch语句中使用instanceof

本文发布于:2023-11-05 19:55:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561694.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   如何在   switch   instanceof

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!