#Execute code in global interceptor after exception filter execution

2 messages · Page 1 of 1 (latest)

tribal escarp
#

I have the following global exception filter:

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
    public catch(exception: unknown, host: ArgumentsHost) {
        const responseData =
            exception instanceof HttpException
                ? this.processBoundedError(exception)
                : this.processUnboundedError(exception);

        const response = host.switchToHttp().getResponse<Response>();

        response.status(responseData.status).json(responseData.body);
    }
}

And I have the following global interceptor:

@Injectable()
export class RequestLifecycleInterceptor implements NestInterceptor {
    public intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
        const request = context.switchToHttp().getRequest<Request>();

        this.loggerService.log("Start handling request", {
            requestParams: request.params,
            requestQuery: request.query,
        });

        const beforeOverallRequest = performance.now();

        return next.handle().pipe(
            tap(() => {
                sendUsageData({
                    requestId: this.clsService.getId(),
                    requestRoute: request.route.path,
                    responseStatusCode: response.statusCode,
                    responseDuration: requestOverallDuration,
                    requestTimestamp: new Date(performance.timeOrigin + beforeOverallRequest).toISOString(),
                }).catch((error) => {
                    this.loggerService.warn("Failed to send usage data", { error });
                });
            }),
        );
    }
}

When I have an exception thrown in my services/controllers, the tap part in the interceptor is not executed. Only when no exceptions are thrown it's executed. I want this part to be executed any way (with/out exceptions). Is it possible?

heavy basin
#

exceptions filters always run after interceptors. Once an exception filter receives the exception, all interceptors have already finished.