NestJS中文文档
微服务 / 异常过滤器
已译 191/191

异常过滤器

HTTP 异常过滤器层与对应的微服务层之间唯一的区别是:微服务应抛出 RpcException 而非 HttpException。

throw new RpcException('Invalid credentials.');
提示

RpcException 类从 @nestjs/microservices 包导入。

Nest 处理抛出的异常,并返回具有以下结构的 error 对象:

{
  "status": "error",
  "message": "Invalid credentials."
}

如果传给 RpcException 构造函数的是对象而不是字符串,Nest 会原样返回该对象。

警告

事件处理器没有响应流。过滤器为 @EventPattern() 处理器重新抛出的错误永远不会到达生产者,因此请在过滤器内部处理该错误。

过滤器

微服务异常过滤器的行为与 HTTP 异常过滤器相同,只有一处差别:catch() 方法必须返回 Observable。

rpc-exception.filter.ts
import { Catch, RpcExceptionFilter, ArgumentsHost } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { RpcException } from '@nestjs/microservices';

@Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
  catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
    return throwError(() => exception.getError());
  }
}
import { Catch } from '@nestjs/common';
import { throwError } from 'rxjs';
import { RpcException } from '@nestjs/microservices';

@Catch(RpcException)
export class ExceptionFilter {
  catch(exception, host) {
    return throwError(() => exception.getError());
  }
}
警告

注册在主 HTTP 应用上的全局异常过滤器不会作用于连接到混合应用的微服务,除非你设置 inheritAppConfig 选项。参见共享配置。

下面的示例使用了手动实例化的方法级过滤器。与基于 HTTP 的应用一样,你也可以使用控制器级过滤器(即在控制器类前加上 @UseFilters() 装饰器)。

@@filename()
@UseFilters(new ExceptionFilter())
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
  return (data || []).reduce((a, b) => a + b);
}
@UseFilters(new ExceptionFilter())
@MessagePattern({ cmd: 'sum' })
accumulate(data) {
  return (data || []).reduce((a, b) => a + b);
}

继承

通常,你会根据应用需求创建完全定制的异常过滤器。不过在某些情况下,你可能希望继承核心异常过滤器,并依据某些因素重写其行为。

要把异常处理委托给基类过滤器,请继承 BaseRpcExceptionFilter 并调用继承而来的 catch() 方法。

@@filename()
import { Catch, ArgumentsHost } from '@nestjs/common';
import { BaseRpcExceptionFilter } from '@nestjs/microservices';

@Catch()
export class AllExceptionsFilter extends BaseRpcExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    return super.catch(exception, host);
  }
}
import { Catch } from '@nestjs/common';
import { BaseRpcExceptionFilter } from '@nestjs/microservices';

@Catch()
export class AllExceptionsFilter extends BaseRpcExceptionFilter {
  catch(exception, host) {
    return super.catch(exception, host);
  }
}

上面的实现只是一个演示该做法的空壳。你对扩展异常过滤器的实现会包含自己的业务逻辑(例如处理各种条件)。