如何在switch语句中使用instanceof [英] How to use instanceof in a switch statement

查看:2815
本文介绍了如何在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆