Error handling trong microservices khác với HTTP — không có response để throw exception trực tiếp.
TCP/Redis transport — throw RpcException:
typescript
@MessagePattern({ cmd: 'get_user' })
async getUser(@Payload() data: { id: number }) {
const user = await this.usersService.findOne(data.id);
if (!user) throw new RpcException({ status: 404, message: 'User not found' });
return user;
}
// Client side — catch error (dùng lastValueFrom thay .toPromise() deprecated trong RxJS 7+)
import { lastValueFrom } from 'rxjs';
await lastValueFrom(
this.client.send<User>({ cmd: 'get_user' }, { id })
.pipe(catchError(err => throwError(() => new NotFoundException(err.message))))
);Dead Letter Queue (DLQ) với RabbitMQ:
typescript
// Setup DLQ binding trong RabbitMQ management
// Messages fail → retry queue → DLQ sau N retries
ClientsModule.register([{
name: 'RABBIT_SERVICE',
transport: Transport.RMQ,
options: {
urls: ['amqp://localhost:5672'],
queue: 'orders_queue',
queueOptions: {
durable: true,
deadLetterExchange: 'dlx', // Failed messages go here
messageTtl: 10000,
},
},
}])Monitoring: log failed messages với correlation ID, alert khi DLQ depth tăng, implement manual replay từ DLQ.