我正在尝试将nestjs-config注入到我创建的以下异常处理程序中:
import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common';
import { HttpException } from '@nestjs/common';
import { InjectConfig } from 'nestjs-config';
@Injectable()
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
constructor(
@InjectConfig()
private readonly config,
) {
this.config = config.get('errors');
}
catch(exception: HttpException, host: ArgumentsHost) {
// some code here that calls this.config
}
}但是它返回了未定义的:TypeError: Cannot read property 'get' of undefined
以下是异常处理程序的全局定义方式:
const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);发布于 2018-09-23 00:11:49
好的,我刚刚意识到,在你的代码中,你在容器之外创建了过滤器,因此ConfigService没有被注入。有几种方法可以解决这个问题。一
ConfigService.load(path.resolve(__dirname, 'config', '*.ts'))
const app = await NestFactory.create(AppModule, { cors: true });
app.useGlobalFilters(new HttpExceptionFilter(ConfigService));
await app.listen(3000);或
const app = await NestFactory.create(AppModule, {cors: true});
const config = app.get<ConfigService>(ConfigService);
app.useGlobalFilters(new HttpExceptionFilter(config));
await app.listen(3000);这取决于您的AppModule如下所示
@Module({
imports: [ConfigModule.load(path.resolve(__dirname, 'config', '*.ts')],
})
export AppModule {}或者像这样:
const app = await NestFactory.create(AppModule, {cors: true});
const httpExceptionFilter = app.get(HttpExpectionFilter);
app.useGlobalFilters(httpExpectionFilter);发布于 2018-09-26 07:30:14
通过调用ConfigService解决了这个问题,方法如下:
export class HttpExceptionFilter implements ExceptionFilter {
constructor(private readonly config: ConfigService) {
this.config = ConfigService.get('errors');
}
catch(exception: HttpException, host: ArgumentsHost) {
// some code here that calls this.config
}
}发布于 2021-07-18 16:44:53
对于Nestjs V8,您可以将其放在AppModule提供程序中:
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
},https://stackoverflow.com/questions/52457899
复制相似问题