我使用自定义错误 ( 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);
};
}
现在我宁愿为这种类型的流程使用一个开关,结果如下:
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然而不是那样工作的。所以后者失败了。
有什么方法可以在 switch 语句中检查其类的实例吗?
最佳答案
一个不错的选择是使用构造函数
property对象的:
// 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);
}
请注意,构造函数
必须与创建对象的构造函数完全匹配(假设 error
是 NotAllowedError
和 的实例NotAllowedError
是 Error
的子类):
error.constructor === NotAllowedError
为true
error.constructor === Error
为false
这与 instanceof
不同,它也可以匹配父类(super class):
错误 instanceof NotAllowedError
为true
error instanceof Error
为true
检查 this interesting post关于 constructor
属性。
关于javascript - 如何在 switch 语句中使用 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36332665/