generic throw giving Expected an object to be thrown lint error
Asked Answered
B

2

49

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

Bangweulu answered 31/10, 2018 at 10:12 Comment(2)
throw new Error(myMessage); developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Nervous
@Nervous but i want to send two properties, Code tooBangweulu
M
60
 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 {
      //...
    }
 }
Maggs answered 31/10, 2018 at 10:17 Comment(0)
B
22

Another simple workaround is store on variable and throw.

const errorMessage =  { code : 403, message : myMessage };
throw errorMessage;
Bangweulu answered 21/11, 2018 at 9:47 Comment(2)
Webstorm doesn't like this: Local variable 'errorMessage' is redundant.Inconformity
This error will not have a stack trace. If that's what you want, it is better to disable the lint rule rather than building a workaround to trick it.Callie

© 2022 - 2024 — McMap. All rights reserved.