#TCP microservice error handeling.

8 messages · Page 1 of 1 (latest)

torpid crow
#

I cant find a good approach for that, basically i want my federation to pass tcp errors from the microservice to my final user http response.

#

( I called it federation but most people call gateway.)

torpid crow
#

solved

#

here's how i did it

#
import { BaseExceptionFilter } from '@nestjs/core';

interface Exception {
  message: string;
  status: number;
}

@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
  catch(exception: Exception, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    let status = 500;
    let message = 'Internal server error';

    if (exception?.message) {
      status = exception?.status;
      message = exception?.message;
    }

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message,
    });
  }
}
#

First you create an all exception filter at the client

#
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './errors/allException.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.useGlobalFilters(new AllExceptionsFilter());

  await app.listen(3000);
}
bootstrap();

your client main.ts should look like this

#
    const unit = await this.unitModel.findOne({ _id: id }).exec();

    if (!unit?._id) {
      throw new RpcException({ message: 'Failed to get unit.', status: 400 });
    }

    return unit;
  }

this is how you return an error inside your microservice