ExceptionFilter正确的解决方案是按照 @eol 指出的那样使用,但为了允许依赖注入,您应该将它们注册在模块上,而不是使用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');
}
}
Run Code Online (Sandbox Code Playgroud)
app.module.ts
@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');
}
}
Run Code Online (Sandbox Code Playgroud)
这也将在全球范围内注册它们。
您可以定义一个自定义全局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');
}
}
Run Code Online (Sandbox Code Playgroud)
您可以按如下方式设置此异常过滤器global:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// ...
app.useGlobalFilters(new NotFoundExceptionFilter());
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8918 次 |
| 最近记录: |