在微服务中避免应用程序崩溃的HTTP异常

huangapple go评论53阅读模式
英文:

avoid app crash in microservice on http Exception

问题

我有一个 Nestjs 微服务应用,

一个网关和用户服务

通过 RabbitMQ 连接

当用户服务发生 Http 异常

会导致应用崩溃

但是在 Rpc 异常 下是可以的

我认为任何 Http 异常 都必须被捕获并且

转换为 Rpc 异常 以避免崩溃。

你知道应该在哪里以及如何处理吗?

或者有没有其他更好的方法来解决这个问题?

英文:

I have Nestjs microservice app ,

a gateway and users service

connected via RabbitMQ

when some Http Exception happens in Users service

it cause app to crash

But it is ok on Rpc Exception

I think any Http Exception must be catched and

converted to Rpc Exception in order to avoid crash.

do you know where and How should It be done ?

or any other better idea to handle this problem ?

答案1

得分: 1

你应该使用自己的逻辑创建一个异常过滤器来序列化错误,这个示例是我从文档中修改的,用于捕获 HttpException 错误并将它们作为可观察对象使用 throwError 返回。

然后,在响应其他微服务的控制器中使用它。

英文:

You should create an exception filter with your own logic of how to serialize your errors, this example I modified from the docs to catch HttpException errors and return them as an observable using throwError

import { ArgumentsHost, Catch, HttpException } from '@nestjs/common';
import { BaseRpcExceptionFilter } from '@nestjs/microservices';
import { throwError } from 'rxjs';

@Catch()
export class CustomExceptionFilter extends BaseRpcExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    if (exception instanceof HttpException) {
      return throwError(() => exception.getResponse());
    }

    return super.catch(exception, host);
  }
}

Then used it on the controller that responds to other microservice

import { Controller, UseFilters, ValidationPipe } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';

import { CustomExceptionFilter } from './custom-exception.filter'

@Controller('users')
@UseFilters(CustomExceptionFilter)
export class UserController {
  @MessagePattern('create.user')
  create(@Payload(ValidationPipe) createUser: CreateUserDTO) {
    return this.userService.create(createUser);
  }
}

huangapple
  • 本文由 发表于 2023年5月21日 03:51:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76297085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定