1

If I use Throw new Error("User not found"), then it gives in response

{status:false,message:"User Not Found"}

But with status code 500, And I need Status 400 in Postman

custom Error using throw function

but if we use res.status(500).send({ status: false, message: "User not found" })

then it gives status code 400, And I need Status 400 in Postman . So, I need same status code in postman only.This is the problem. Tyler2P and Abin Bala , I followed your code but I am unable to get desired status code in postman status.

2
  • Does this answer your question? Throwing an error in node.js Commented Jan 24, 2023 at 7:07
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Jan 24, 2023 at 9:34

1 Answer 1

0

You can create a custom error class as below and throw it with appropriate message and httpCode. You can also add more properties. Then you can catch the custom error object using the catch block and get the required values.

class CustomError extends Error {
  name;
  httpCode;
  message;
  
  
  constructor(name,httpCode, message){
    super(message);
    this.name = name;
    this.httpCode = httpCode;
    this.message = message;
  }
}

errorThrowingFunction.js:

//import the custom error class in the module that you //are   going to use it.
errorThrowingFunction = () => {
  const authToken = myCache.get("token");
      
  if (!authToken) {
    throw new CustomError('Error',401,'token missing');
  } else {
    return authToken;
  }
}

index.js:

handler = () => {
  try {
    errorThrowingFunction();
  } catch(error){
    const response = {
      statusCode: error.httpCode,
      body: JSON.Stringify(error.message),
      isBase64Encoded: false,
      //add other headers
    }
    return response;
    //if you are using this in rest service, the use below line
    //return res.status(error.httpCode)send(response);
  }
}
Sign up to request clarification or add additional context in comments.

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.