Javascript 如何在 switch 语句中使用 instanceof

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36332665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:56:29  来源:igfitidea点击:

How to use instanceof in a switch statement

javascripterror-handlingecmascript-6

提问by alextes

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

我使用自定义错误 ( es6-error) 允许我根据它们的类处理错误,如下所示:

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);
      }
    });
}

instanceofdoesn't work like that however. So the latter fails.

但是,instanceof不是这样工作的。所以后者失败了。

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

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

回答by Dmitri Pavlutin

A good option is to use the constructorpropertyof the object:

一个不错的选择是使用对象的constructor属性

// 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);
}

Notice that the constructormust match exactly with the one that object was created (suppose erroris an instance of NotAllowedErrorand NotAllowedErroris a subclass of Error):

请注意,constructor必须与创建的对象完全匹配(假设error是 的实例NotAllowedError并且NotAllowedError是 的子类Error):

  • error.constructor === NotAllowedErroris true
  • error.constructor === Erroris false
  • error.constructor === NotAllowedErrortrue
  • error.constructor === Errorfalse

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

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

  • error instanceof NotAllowedErroris true
  • error instanceof Erroris true
  • error instanceof NotAllowedErrortrue
  • error instanceof Errortrue

Check this interesting postabout constructorproperty.

查看这篇关于constructor财产的有趣帖子

回答by ya_dimon

Workaround, to avoid if-else. Found here

解决方法,以避免if-else。在这里找到

switch (true) {
    case error instanceof NotAllowedError: 
        return res.send(400);

    case error instanceof DatabaseEntryNotFoundError: 
        return res.send(404);

    default:
        log('Failed to do something async with an unspecified error: ', error);
        return res.send(500);
}

回答by Lachlan Young

An alternative to this switch case is to just have a status field in the Error's constructor.

这种 switch case 的替代方法是在 Error 的构造函数中只有一个 status 字段。

For Example, build your error like so:

例如,像这样构建你的错误:

class NotAllowedError extends Error {
    constructor(message, status) {
        super(message);
        this.message = message;
        this.status = 403; // Forbidden error code
    }
}

Handle your error like so:

像这样处理你的错误:

.catch((error) => {
  res.send(error.status);
});