Problem:
I have a custom NPM package comprising utilities shared across different microservices built with Nest JS. The problem is that when AuthGuard throws an error with some data from my package, the Nest application catches it but only throws the default error. I am throwing the HttpException
error with some data and I want the Nest application to throw the same data as response instead of the default.
Code:
The auth guard in the package is a simple guard that verifies the token and returns a response or an error
import { CanActivate, ExecutionContext, Injectable, HttpException } from '@nestjs/common';
import { verifyToken } from '../helpers';
@Injectable()
export class AuthGuard implements CanActivate {
constructor() {}
async canActivate(context: ExecutionContext): Promise<any> {
const request = context.switchToHttp().getRequest();
try {
const token = request.headers.authorization?.split(' ')[1];
return await verifyToken(
token,
);
} catch (error) {
console.log('⛈️⛈️⛈️⛈️⛈️⛈️', error);
throw new HttpException(
{
errorDetails: "Token Expired",
},
401,
);
}
}
By this logic, I should be getting the error in the format of
{
errorDetails:"Token Expired"
}
but the NEST return a default error
{
"statusCode": 500,
"message": "Internal server error"
}
I have tried to create a Nest Module for the AuthGuard and import it into my app.module but it didn’t work. I have created global exception filter for it but it didn’t work also.
The same code works if I place it in a file inside my application.