My goal is to implement error handling for all http requests using custom decorators. Here's my current code snippet:
createRecord(data: data) {
return this.httpClient.post(`${this.apiURL}/record/`, data);
}
I am looking to refactor these functions to incorporate error handling by modifying them like so:
createRecord(data: data) {
return this.httpClient.post(`${this.apiURL}/record/`, data)
.pipe(tap((data)=>console.log(data)),catchError(handleError)));
}
Although I am aware that this can be achieved using http interceptors, I attempted it with custom method decorators instead. The custom decorator I created appears as follows:
export function CatchHttpError() : MethodDecorator {
return function ( target : any, propertyKey : string, descriptor : PropertyDescriptor ) {
const original = descriptor.value;
descriptor.value = original()
.pipe(
tap((data)=>console.log('tap entered: data = ',data)),
catchError(handleError)
);
return descriptor;
};
}
In order to utilize the decorator, I decorate the function in this manner:
@CatchHttpError()
createRecord(data: data) {
return this.httpClient.post(`${this.apiURL}/record/`, data);
}
The issue here lies in the fact that the function executes upon initializing the service, rather than when calling the createRecord method. How can I adjust the method decorator to achieve the desired behavior?