Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use instanceof in a switch statement

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 doesn't work like that however. So the latter fails.

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

like image 259
alextes Avatar asked Mar 31 '16 11:03

alextes


People also ask

Can I use Instanceof with interface?

instanceof can be used to test if an object is a direct or descended instance of a given class. instanceof can also be used with interfaces even though interfaces can't be instantiated like classes.

Can I use Instanceof?

The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.

What is the use of Instanceof operator?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .


2 Answers

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

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 is true
  • error.constructor === Error is false

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

  • error instanceof NotAllowedError is true
  • error instanceof Error is true

Check this interesting post about constructor property.

like image 127
Dmitri Pavlutin Avatar answered Oct 05 '22 23:10

Dmitri Pavlutin


Workaround, to avoid if-else. Found here

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); } 
like image 24
ya_dimon Avatar answered Oct 05 '22 23:10

ya_dimon