我正在嘗試向例外過濾器注入依賴項。
這是我的依賴:
@Injectable()
export class SmsService {
constructor() {}
async create() {
console.log('sms created');
}
}
及其模塊:
@Module({
providers: [SmsService],
exports: [SmsService],
})
export class SmsModule {}
我的例外過濾器在這里:
@Catch(InternalServerErrorException)
export class InternalServerErrorFilter implements ExceptionFilter {
@Inject(SmsService)
private readonly smsService: SmsService;
async catch(exception: InternalServerErrorException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
// smsService is undefined so create property is undefined
await this.smsService.create();
response.status(exception.getStatus()).send({
message: 'Something went wrong our side.',
statusCode: exception.getStatus(),
});
}
}
我的應用模塊:
@Module({
imports: [SmsModule, MailsModule],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_FILTER,
useClass: InternalServerErrorFilter,
},
],
})
export class AppModule {}
我的 main.ts 檔案:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new InternalServerErrorFilter());
await app.listen(3000);
}
bootstrap();
我的應用服務終于來了。
@Injectable()
export class AppService {
getHello(): string {
throw new InternalServerErrorException();
}
}
它只是拋出內部服務器錯誤例外來執行內部服務器錯誤過濾器。
當我向 http://localhost:3000 發送請求時,它會引發如下錯誤:
/* await this.smsService.create();
^
TypeError: Cannot read properties of undefined (reading 'create')
*/
我的應用程式成功啟動,所以看起來沒有依賴錯誤。
uj5u.com熱心網友回復:
如果我記得,受約束的增強器useGlobal*()優先于APP_*提供者(需要仔細檢查)。通過使用new,您負責設定該類實體所需的所有內容,無論它是否@Inject()在屬性或建構式中具有裝飾器。只是設定 Nest 可以讀取的@Inject()元資料,因此它知道在類實體化期間要設定什么。因此,當您通過new InternalServerErrorFilter()并且從未設定smsService時,您會在運行時收到錯誤,因為該服務從未定義,只是宣告。
如果您要使用全域增強器,我強烈建議只保留一種全域增強器系結型別,甚至更強烈建議只使用APP_*系結,因為它們更容易與您的應用程式和 e2e 測驗保持一致,另外Nest 可以對通過以下方式系結的增強器進行 DIAPP_*
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/514937.html
