最近重新使用nestjs重构了老系统,新系统补充了缺少的模调上报和监控,这里记录下如何在NestJS框架中上报调用结果。本文主要介绍如何使用Nestjs全局过滤器和全局拦截器来实现此功能
首先,我们创建一个全局过滤器来捕获并上报异常。以下是一个简单的全局过滤器示例:
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Injectable } from '@nestjs/common';
import { ErrorReportingService } from './error-reporting.service';
@Injectable()
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
constructor(private readonly errorReportingService: ErrorReportingService) {}
catch(exception: HttpException, host: ArgumentsHost) {
this.errorReportingService.report(exception);
// 处理异常并生成响应, 可以统一返回数据的结构
}
}
接下来,我们创建一个全局拦截器来上报正常的API调用结果。以下是一个简单的全局拦截器示例:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { ResultReportingService } from './result-reporting.service';
@Injectable()
export class ResultInterceptor implements NestInterceptor {
constructor(private readonly resultReportingService: ResultReportingService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
tap(result => this.resultReportingService.report(context, result)),
);
}
}
为了在全局过滤器和拦截器中使用依赖注入,我们需要将它们注册到模块中,然后在main.ts
中获取这些实例并注册。以下是修改后的示例:
AppModule
中注册全局过滤器和拦截器:import { Module } from '@nestjs/common';
import { APP_FILTER, APP_INTERCEPTOR } from '@nestjs/core';
import { HttpExceptionFilter } from './http-exception.filter';
import { ResultInterceptor } from './result.interceptor';
import { ErrorReportingService } from './error-reporting.service';
import { ResultReportingService } from './result-reporting.service';
@Module({
providers: [
ErrorReportingService,
ResultReportingService,
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
},
{
provide: APP_INTERCEPTOR,
useClass: ResultInterceptor,
},
],
})
export class AppModule {}
main.ts
中获取全局过滤器和拦截器的实例并注册:import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './http-exception.filter';
import { ResultInterceptor } from './result.interceptor';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const httpExceptionFilter = app.get(HttpExceptionFilter);
const resultInterceptor = app.get(ResultInterceptor);
app.useGlobalFilters(httpExceptionFilter);
app.useGlobalInterceptors(resultInterceptor);
await app.listen(3000);
}
bootstrap();
现在,在全局过滤器和拦截器中,我们可以使用依赖注入的服务。这样,我们就可以在整个应用程序中上报调用结果,并在全局过滤器和拦截器中灵活地使用各种服务。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。