我使用nestjs来处理所有API。如果找不到路由,我想显示 404 页面。
正确的解决方案是按照@eol指出的使用ExceptionFilter
,但要允许依赖注入,您应该将它们注册到模块上,而不是使用useGlobalFilters
(如文档中指出的那样(:
@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
catch(_exception: NotFoundException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.sendFile('./path/to/your/404-page.html');
}
}
app.module.ts
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
@Module({
providers: [
{
provide: APP_FILTER,
useClass: NotFoundExceptionFilter,
},
],
})
export class AppModule {}
这也将在全球范围内注册它们。
您可以定义一个自定义全局ExceptionFilter
来捕获NotFoundException
异常,然后相应地处理错误:
@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
catch(exception: NotFoundException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.sendFile('./path/to/your/404-page.html');
}
}
您可以按如下方式设置此异常筛选器global
:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// ...
app.useGlobalFilters(new NotFoundExceptionFilter());
await app.listen(3000);
}
bootstrap();