How I can intercept errors from passport strategies in nestjs?

Viewed 2250

I created an auth module using nestjs and two passport strategies: passport-facebook, passport-google-oauth20. Everything works fine, except when it's not

If there's an error in a passport strategy, the server return 500 error instead of a error thrown by a strategy. For example, if the token from identity provider been used already we got FacebookTokenError: This authorization code has been used. (passport-facebook) or TokenError: Bad Request (passport-google-oauth20) message in the console but server return 500 error.

What is the nestjs way to return proper errors in that case?

Also, can somebody explain why we need 2 routes (auth/google and auth/google/callback) when just one (auth/google with @UseGuards(AuthGuard('google'))) works fine?

1 Answers

In case anyone stuck with the same issue I wanna post an answer. You need to implement your AuthGuard. For example:

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class FacebookAuthGuard extends AuthGuard('facebook') {
  constructor() {
    super();
  }

  handleRequest(err: any, user: any, info: any, context: any, status: any) {
    console.log('errorGuard', err);
    if (err || !user) {
      throw new HttpException(err.message, err.status);
    }
    return user;
  }
}

In handleRequest method you can get all info about error you need. The 500 error was thrown by a passport strategy itself.

Related