I have a global guard that is registered in the application in common.module.ts
which is a global module.
const HeaderGuardGlobal = {
provide: APP_GUARD,
useClass: HeaderGuard
};
@Global()
@Module({
imports: [ LoggerModule ],
providers: [ HeaderGuardGlobal ],
exports: []
})
header.guard.ts:
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const userName = request.headers[HEADERS.USER_NAME];
if(!userName) {
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}
I have a control-scoped interceptor authenticate-header.interceptor.ts
@Injectable()
export class setAuthenticateHeaderInterceptor<T> implements NestInterceptor<T, Response<T>> {
public constructor() {}
intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
const req = context.switchToHttp().getRequest();
const res = context.switchToHttp().getResponse();
return next
.handle()
.pipe(
catchError(err => {
console.log('ERROR: ', err);
res.setHeader('sampleKey', 'sampleValue');
return throwError(err);
})
)
}
}
user.controller.ts:
@Controller('user')
@UseInterceptors(setAuthenticateHeaderInterceptor)
export class ClientController {
What I'm trying to achieve is that when header.guard.ts
throws Forbidden
exception, the authenticate-header.interceptor.ts
would catch the exception and will propagate it to the global http-filter, but before doing that I want to add a header to the response object.
The issue I'm facing is when the exception is being thrown by the guard, the interceptor is unable to catch it. However, when the same error is thrown either from the route handler or from service, the interceptor is able to catch it.
I went through the request-lifecycle to understand the execution context, and found the below statement in interceptors section.
any errors thrown by pipes, controllers, or services can be read in the catchError operator of an interceptor.
The statement doesn't say anything about guards, so I'm assuming what I'm trying to achieve is not possible.
I'm unable to figure out why an error thrown inside a guard is not being caught by the interceptor. The above code snippets only include the parts which I thought were necessary for the question, if anybody feels like more info is needed. then I'll provide it.