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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With