1

I was working with this API and everything was fine until I've tried POST method.

Now what happens is, when I try to send data from postman, NodeJS app crashes, displaying this error: HTTPError: Response code 400 (Bad Request) and pointing that error is called in the catch part.

So thing is, when I directly send post request to the API directly (not with my localhost server) it returns 400: Bad request with message that data is not correct. Now everything is okay when I send it directly, but when I try to call the API with my localhost it throws that error.

The error is throw from the call: got.post(...) which uses this library: https://www.npmjs.com/package/got

Is it possible to make that call and get the 400 response without getting an error raised from the call?

methods.ts

export const addReservation = async (postData: object) => {
  const url = API_URL + '/reservation';

  try {
    const response = await got.post(url, {
      json: { ...postData },
      responseType: 'json',
    });
    
    console.log(response.statusCode); //no success, jumps to the catch block
    return response.body;
  } catch (error) {
    throw new Error(error);
  }
};

reservation.ts

export const reservationHandler = async (req: Request, res: Response) => {
  let postData = req.body;

  let response = await addReservation(postData);
  return res.status(201).json(response); //if all is OK it will return 201, but if not 400
};

So I've tried catching the status code in addReservation but no success. I was having idea by handling cases of status codes 400 or 201, but only proceeds with try block if the status is 201, but if it is 400, it crashes the app.

3
  • Well the answer is probably in the implementation of the library that you're using to do: got.post(...). I'm not familiar with that library, you should provide more context about it in the question. Commented Apr 14, 2021 at 8:39
  • It's a npm package used for http requests, similar as axios. npmjs.com/package/got Commented Apr 14, 2021 at 8:41
  • I specifically asked to do it "in the question" and not in the comment section because we want the readers to be able to have all the relevant context in the question, they shouldn't have to look for it in the comment section. I'll edit the question and add it for you. Glad the problem is solved. Commented Apr 14, 2021 at 9:26

1 Answer 1

2

You have to set throwHttpErrors to false in got options.

https://github.com/sindresorhus/got#throwhttperrors

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.