I need a NestJS interceptor that archives requests, both in exceptional and happy-path cases. Created as follows:
public intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
if (!this.reflector.get<boolean>(RequestMetaData.IS_PUBLIC_ROUTE, context.getHandler())) {
return next.handle().pipe(
map(data => {
const host = context.switchToHttp();
const req = host.getRequest();
const resp = host.getResponse();
this.persistRequest(data, req, resp)
.then(() => this.logger.log(`Request logged`))
.catch(e => {
this.logger.error(`Error logging request: ${e.message}`);
});
return data;
}));
}
return next.handle();
}
Problem:
This only logs the happy path. Because I'm not familiar with RxJS I created another to persist errors. Eg:
public intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next
.handle()
.pipe(
catchError(err => {
return throwError(err);
})
);
}
How can I define a single interceptor that archives both paths?