是否可以在nestjs中显示未找到路由的404页面?

Vis*_*yan 8 node.js nestjs

我使用 Nestjs 来处理所有 api。如果找不到路线,我想显示 404 页面。

thi*_*ign 8

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)

这也将在全球范围内注册它们。


eol*_*eol 5

您可以定义一个自定义全局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)