generic throw giving Expected an object to be thrown lint error

Munna Babu picture Munna Babu · Oct 31, 2018 · Viewed 7.8k times · Source

Below throw code giving lint error Expected an object to be thrown no-throw-literal

throw { code : 403, message : myMessage };

if i try throw new Error, i am not getting eslint but it gives [Object Object] in the response.

throw new Error({ code : 403, message : myMessage });

Could someone tell me how to fix Expected an object to be thrown error ? without removing eslint config/rules

Answer

Jonas Wilms picture Jonas Wilms · Oct 31, 2018
 throw Object.assign(
   new Error(myMessage),
   { code: 402 }
);

Throw a regular error and extend it with custom fields.


You could also write a reusable error class for that:

  class CodeError extends Error {
   constructor(message, code) {
    super(message);
    this.code = code;
   }
 }

 throw new CodeError(myMessage, 404);

That way, you can distinguish the errors easily on catching:

  } catch(error) {
    if(error instanceof CodeError) {
      console.log(error.code);
    } else {
      //...
    }
 }