Search code examples
angularangular-http-interceptors

Angular: HttpInterceptor with different handling for specific situation


I know there is in Angular the HTTPInterceptor:

@Injectable()
export class HTTPRequestInterceptor implements HttpInterceptor {

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap(
        (_response: HttpEvent<any>) => {
          // nothing to do ... ... used for sending anyway...
        },
        (error: HttpErrorResponse) => {
         ... // display message
        }

To my understanding this is applied to all of my requests. Now I have the situation that for one specific request I do not want to apply the regular error handling. Is there an easy way to achieve this? e.g. setting some special parameters in my request

this.http.get<MyInfo>(`getlastInfo/${id}`).toPromise();

Solution

  • As BELLIL suggested, reading a header is easier than relying on the url. You could still remove the header before sending it to the server :

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
        const doSpecificHandling = req.headers.has('Angular-Error-Handler');
    
        return next.handle(req.clone({
          headers: req.headers.delete('Angular-Error-Handler')
        })).pipe(
          tap(
            (_response: HttpEvent<any>) => {
              // nothing to do ... ... used for sending anyway...
            },
            (error: HttpErrorResponse) => {
              if (doSpecificHandling) {
                //handle error for specific case
              } else {
                //handle error for generic case
              }
            }
          )
        );
      }

    With the request:

    this.http.get<MyInfo>(`getlastInfo/${id}`, {
      headers: new HttpHeaders().set('Angular-Error-Handler', 'diff'),
    }).toPromise();