【问题标题】:Nestjs middleware does not throw any errorsNestjs 中间件不会抛出任何错误
【发布时间】:2021-03-30 08:02:33
【问题描述】:

通常在 express 中,任何中间件都可以根据正常的 node-js 回调约定调用 next 并带有可选错误。

但是,当我在 NestMiddleware 中返回错误时,根本不会处理该错误。错误不会被记录或返回,它会被吞下并且请求不会终止。

这里是示例代码:

@Injectable()
export class AuthenticateMiddleware implements NestMiddleware {
  async use(req: Request | any, res: Response, next: NextFunction) {
    console.log(
      chalk.magentaBright.bold('Authenticate Middleware Executing...'),
    );

    let token: string;
    if (
      !req.headers.authorization ||
      !req.headers.authorization.startsWith('Bearer')
    ) {
      return new UnauthorizedException('Please login to continue');
    } else {
      token = req.headers.authorization.split(' ')[1];
    }

    let isValid: { id: string; iat: number; exp: number };
    try {
      isValid = await jwt.verify(token, process.env.JWT_SECRET);
    } catch (e) {
      return new UnauthorizedException('Token invalid!');
    }

    req.userId = isValid.id;
    next();
  }
}

【问题讨论】:

    标签: node.js nestjs


    【解决方案1】:

    您是returning 错误,表示系统认为返回的内容正常。如果您想实际发生错误,则应改为throw 错误。你可以提出同样的论点

    sayHello() {
     return new BadRequestException('Goodby World');
    }
    

    不会抛出错误,因为它不会。您应该在以后的系统中使用throw 关键字来catch 并正确处理它

    【讨论】:

    • 到处使用throw而不是return是个好习惯吗?基本上,我只是问在处理错误时应该在哪里使用return,在哪里应该使用throw
    • return 当你有一个值时。 throw 出现错误时。 Nest 的 ExceptionFilter 将捕获错误,只要它在请求生命周期中
    【解决方案2】:

    在 catch 块中:

    const errPayload =  new UnauthorizedException('Token invalid!');
    next(errPayload)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-18
      • 1970-01-01
      • 2017-02-16
      • 1970-01-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 2016-12-13
      相关资源
      最近更新 更多