我使用自定义错误( 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
发布评论