Search code examples
nestjs

Can't throw UnauthorizedException inside Guard (NestJs)


I want to throw an error in one of my guards, however, this operation is not performed.

canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    return new Promise((resolve, reject) => {
      const request = context.switchToHttp().getRequest();
      const token = request.headers['token'] as string;
      this.authService
        .getUserFromAuthenticationToken(token, false)
        .then((user) => {
          if (user) resolve(true);
          else throw new UnauthorizedException(); **HERE**
        });
    });
  }

If I use resolve(false) instead of "throw new UnauthorizedException", it automatically gives error 403 and there is no problem.

However, when I trow UnauthorizedException, the application crashes and show this error in console :

UnauthorizedException: Unauthorized.

Does anyone have a solution?


Solution

  • After debugging and checking NestJs Codes in(guards-consumer.js), I realized that I should return Observable.

    It works like this:

    canActivate(context: ExecutionContext): Observable<boolean> {
        const request = context.switchToHttp().getRequest();
        const token = request.headers['token'] as string;
        return from(
          this.authService.getUserFromAuthenticationToken(token, false),
        ).pipe(
          map((user) => {
            if (user) return true;
            else throw new UnauthorizedException();
          }),
        );
      }