Hello I'm trying to create a RestFul application using NestJs and I'm trying to create a global exception filter.
Basically I have to 2 endpoints.
/api/user/register
/api/auth/token
Each endpoint throws a different exception but I can't seem to get it working. It doesn't go through my ExceptionFilter class. Did I miss something?
I would really appreciate if someone can help me with this.
Thanks a lot.
AuthModule.ts
@Module({
imports: [
MongooseModule.forFeature([
{
name: 'AuthClient',
schema: AuthClientSchema,
}
]),
],
controllers: [AuthController],
providers: [
AuthService,
],
})
export class AuthModule { }
UserModule.ts
@Module({
imports: [
MongooseModule.forFeature([
{
name: 'User',
schema: UserSchema,
}
]),
],
controllers: [UserController],
providers: [UserService],
})
export class UserModule { }
AppModule.ts
@Module({
imports: [
DatabaseModule,
AuthModule,
UserModule,
],
providers: [
{
provide: APP_FILTER,
useClass: HttpExceptionFilter,
}
],
})
export class AppModule { }
Controller.ts
export class UserController {
@Post('register')
public register(@Body() registerDto: RegisterDto, @Res() res: Response): void {
return this.userService.create(registerDto);
}
}
export class AuthController {
@Post('auth')
public createToken(@Body() authDto: AuthDto, @Res() res: Response): void {
this.authService.findByUsername(authDto).then((data) => {
.....
})
}
}
Providers.ts
@Injectable()
export class AuthService {
async findByUsername(authDto: AuthDto) {
throw new HttpException('Opps something went wrong', 500);
}
}
@Injectable()
export class UserService {
async create(registerDto: RegisterDto) {
throw new HttpException('Unable to create', 500);
}
}
HttpExceptionFilter.ts
@Catch(HttpException)
export class HttpExceptionFilter extends BaseExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost): void {
console.log('<<<<<<>>>>>>>>>>>>>>>>>', exception)
}
}
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
await app.listen(3000);
}
bootstrap();
Repo: click here