typescript Nestjs抛出NotFoundException而不是MethodNotAllowedException

sr4lhrrt  于 12个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(97)

我使用NestJS开发了一个Rest API。当用户使用错误的HTTP方法调用端点时,我需要返回一个自定义的错误响应。
例如,我有一个端点GET /cats,当用户使用POST或PUT调用它时,我想返回一个Method Not Allowed响应,但nestjs抛出了NotFoundException而不是MethodNotAllowedException
PS:在异常过滤器中,我处理不存在的路由的NotFoundException,但我想处理用错误方法调用的路由的MethodNotAllowedException

import { Controller, Get } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}

字符串

yrdbyhpb

yrdbyhpb1#

由于我的控制器的复杂性,我选择不使用@All装饰器解决方案来检查处理程序中的方法,而是开发了一个路由过滤器中间件。

import { Injectable, MethodNotAllowedException, NestMiddleware, NotFoundException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NextFunction, Response,Request } from 'express';
import * as pathToRegexp from 'path-to-regexp';

@Injectable()
export class RouteFilterMiddleware implements NestMiddleware {
  private routes = [
    { path: '/status', allowedMethods: ['GET'] },
    { path: '/cats/:id', allowedMethods: ['GET','POST'] },
  ];

  constructor(private readonly configService: ConfigService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const apiPrefix = this.configService.get('app.apiPrefix');
    const endpoint = req.url.replace(`/${apiPrefix}`, '');

    const matchingRoute = this.routes.find((route) => {
      const regex = pathToRegexp(route.path);
      return regex.test(endpoint);
    });

    if (!matchingRoute) {
      throw new NotFoundException();
    }

    if (matchingRoute.allowedMethods.includes(req.method)) {
      next();
    } 
      throw new MethodNotAllowedException();
  }
}

字符串

相关问题