0
votes

I know NestJS handle all the status code who are different from 200-299 as an error, and I already created my own HttpExceptionFilter implements ExceptionFilter to handle errors.

Well, this is my current scenario. One of my providers is sending me the response with status code 500 in case a value is wrong (not a real server error), but in the response it comes the message and description.

Is there a way to catch inline the exception without transfer the response to my ExceptionFilter?

const options = {
      requestBody,
      headers: {
        Authorization: `Bearer 12345`,
        'Content-Type': 'text/plain',
      },
      data: requestBody,
    };


    const endpoint = http://myclientendpoint.com;

    try {
      const response = await this.httpService
        .post(endpoint, requestBody, options)
        .toPromise();
      if (
        response == null ||
        response == undefined ||
        response.data == null ||
        response.data == undefined
      ) {
        return null;
      }
      console.log(response.data);

      return await response.data;
    } catch (error) {
      console.log('>>> THIS IS TRIGGERED WITHOUT THE RESPONSE BODY');
      console.log(error);
      return null;
    }
1

1 Answers

0
votes

It is possible adding a try catch and getting the body content with: error.response.data

This is the example:

try {
      const response = await this.httpService
        .post(endpoint, requestBody, options)
        .toPromise();
      if (
        response == null ||
        response == undefined ||
        response.data == null ||
        response.data == undefined
      ) {
        return null;
      }
      console.log(response.data); 

      return await response.data;
    } catch (error) {
      if (error.response.status === 500) {
        console.log('> TRYING TO HANDLED 500 status code');
        console.log(error.response.data);
        return error.response.data;
      }
      if (error.response.status === 403) {
        console.log('> TRYING TO HANDLED 403 status code');
        console.log(error.response.data);
        return error.response.data;
      }
      if (error.response.status === 505) {
        console.log('> TRYING TO HANDLED 505 status code');
        console.log(error.response.data);
        return error.response.data;
      }

      console.log(error);

      return null;
    }