Global filter or interceptor get dependency as undefined
When I use Exception filters
as exception-filters#binding-filters say,register a global-scoped filter in providers
。I get a wrong message:
(node:37173) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'reportOppProcess' of undefined
// app.module.ts
@Module({
imports: [
MonitorModule,
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
},
],
})
export class AppModule {}
// http-exception.filter.ts
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
import { MonitorService } from '../monitor/monitor.service';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
constructor(private monitor: MonitorService) {}
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const request = ctx.getResponse<Request>();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
response.status(status).json({
statusCode: status,
code: 0,
msg: exception.message,
});
this.report(request, response, 0);
}
async report(req: Request, res: Response, duration: number): Promise<void> {
const reportInfo = {
apiName: req.url,
operation: req.method,
code: '0',
status: res.statusCode,
success: res.statusCode >= 500 ? 1 : 0,
duration,
addition: '',
};
this.monitor.reportOppProcess(reportInfo);
}
}
I think monitor
should be injected, but this.monitor
is undefined when running。
Nest version: 7.0.8
For Tooling issues:
- Node version: 12.14.1
- Platform: Mac
Others:
Please provide a minimum reproduction.
If you are using any REQUEST scoped providers in your enhancers, they will not be resolved properly. This can lead to the injected value being undefined.
If you are using any REQUEST scoped providers in your enhancers, they will not be resolved properly. This can lead to the injected value being undefined.
This can be fixed with changing this:
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
},
to this:
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
scope: Scope.REQUEST
},
@kamilmysliwiec you learn something new every day. Thank you :smile_cat:
@kamilmysliwiec That works for me. Thank you
Most helpful comment
This can be fixed with changing this:
to this: