3

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?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Appreciate your answer. Are there any other ways where I can throw an error like a JSON object?
This object will be in the console right?. But I want to get it to the window as a json response
Yes. What do you mean by "to the window"?
I got it buddy. Thanks:)
Ok but can you still explain what you meant so I know?
1

You can't throw an object as an error. The Error constructor doesn't support that. Another approach is to have the custom object in a separate property. You can get that custom object out in the catch block:

export type ApiError = {
  statusCode: number;
  code: number;
};

export class AuthenticationException extends Error {
  public apiError: ApiError;

  constructor(message: string, apiError: ApiError, options?: ErrorOptions) {
    super(message, options);

    this.apiError = apiError;
    this.message = message;
  }
}

try {
  throw new AuthenticationException('Unable to decode token', {
    code: 1234,
    statusCode: 401,
  });
} catch (e) {
  if (e instanceof AuthenticationException) {
    console.log(e.message);
    console.log(e.apiError);
  }
}

Console output:

Unable to decode token
{
  "code": 1234,
  "statusCode": 401
}

Reference:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.