I have some APIs that need to handle business logic if the API throws any error. At this point, I use an interceptor to handle the errors for any APIs. This works fine but this does not allow me to call the "error" part in subscribe. Below am specifying a sample snippet for the current scenario:
interceptor
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpErrorResponse, HttpEvent, HttpRequest, HttpHandler } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { ToastrService } from 'ngx-toastr';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private toastr: ToastrService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((err, caught: Observable<HttpEvent<any>>) => {
if (err instanceof HttpErrorResponse) {
this.toastr.error(!err.error.message ? 'Internal Server Error' : err.error.message);
return of(err as any);
}
throw err;
})
);
}
}
What I want is the interceptor to work as it is and let me write business logic in the error part of subscribing as below:
component
constructor(private http: HttpClientService) {}
sampleMethod() {
this.http.getAllData().subscribe({
next: response => { ... work on success response },
error: error => { ... perform specific task required on error scenario } // This is not running until & unless I write logic to skip this certain API in interceptor
});
}
I have shown here using a single API but in my requirement, I have multiple scenarios where I need to write the logic in the error part and I don't want to write much logic in the interceptor.
Can anyone provide me with any example of how to achieve this scenario?