如何在switch语句中使用instanceof [英] How to use instanceof in a switch statement
问题描述
我使用自定义错误( 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
istrue
error.constructor === Error
isfalse
这与 instanceof
有所不同,它也可以匹配超级类:
This makes a difference from instanceof
, which can match also the super class:
-
错误实例NotAllowedError
是true
-
error instanceof错误
是true
error instanceof NotAllowedError
istrue
error instanceof Error
istrue
检查这个有趣的帖子关于构造函数
财产。
这篇关于如何在switch语句中使用instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!