Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw custom object as Error in Javascript

I'm extending Error object here and passing the status code, code and the message.

class AuthenticationException extends Error {
constructor(statusCode, code, message) {
super();
this.statusCode = statusCode;
this.message = message;
this.code = code;
}
}
export default AuthenticationException;

But the Error throws only like below

{
"error": "Unable to decode token"
}

But this is not what i was looking for. The result should be like,

{
"message": "Unable to decode token",
"code":1234
}

Please help me If you can. And can I get many key-value pair as throw exception?

like image 242
ahkam Avatar asked Jun 05 '26 23:06

ahkam


1 Answers

My guess is that the call to super() throws before the assignments run. But since super() needs to be called before accessing this, you may be out of luck.

Even if you could skip super(), you'd need to find a way of telling the Error class to print not only message but also code and statusCode.

What you're trying to do can be achieved by just throwing the object you need:

throw { message: '...', code: '...', statusCode: '...' }

Or, if you use this in a bunch of places and don't want to keep typing out the object, use a function:

let customThrow = (message, code, statusCode) => {
  throw { message, code, statusCode };
}

There's no need for classes, let alone inheritance. Much simpler this way.

like image 125
weltschmerz Avatar answered Jun 07 '26 11:06

weltschmerz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!