Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic throw giving Expected an object to be thrown lint error

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

like image 363
Munna Babu Avatar asked Oct 31 '18 10:10

Munna Babu


People also ask

How do you handle throwing a new Error?

throw new Error()Creating objects using ES6 classes requires the use of new and extending Error via a class is the only way to preserve stack traces. throw Error() is like a Javascript string, a number, a boolean, or an object. It returns specific errors as defined in the message value which is passed as an argument.

What is throw Error in JavaScript?

When an error occurs, JavaScript will normally stop and generate an error message. The technical term for this is: JavaScript will throw an exception (throw an error). JavaScript will actually create an Error object with two properties: name and message.

Can you throw custom exception with Error object?

While the majority of exceptions are implementations of the global Error class, any old object can be thrown. With this in mind, there are two ways to throw an exception: directly via an Error object, and through a custom object.

How do you throw an object in JavaScript?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.


2 Answers

 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 {
      //...
    }
 }
like image 109
Jonas Wilms Avatar answered Oct 19 '22 20:10

Jonas Wilms


Another simple workaround is store on variable and throw.

const errorMessage =  { code : 403, message : myMessage };
throw errorMessage;
like image 45
Munna Babu Avatar answered Oct 19 '22 18:10

Munna Babu