Sachin Yadav
Sachin Yadav

Reputation: 313

Nestjs middleware does not throw any errors

Normally in express, any middleware can call next with an optional error, as per the normal node-js callback conventions.

But, when I return error inside of a NestMiddleware, the error is not handled at all. The error is not logged or returned, it is swallowed and the request does not terminate.

Here is the sample code:

@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();
  }
}

Upvotes: 1

Views: 4893

Answers (2)

Darren Zou
Darren Zou

Reputation: 3744

In the catch block:

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

Upvotes: 3

Jay McDoniel
Jay McDoniel

Reputation: 70121

You're returning errors, meaning the system thinks what has been returned is fine. If you want to actually have an error happen, you should throw the error instead. You could make the same argument that

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

doesn't throw an error, because it doesn't. You should be using the throw keyword for a later system to catch it and handle it properly

Upvotes: 3

Related Questions