2

I want to implement an HttpInterceptor in order to handle a 404 error. For now I just want to log something in the console when the HttpInterceptor is reached.

I implement a basic doNothing HttpInterceptor but nothing work.

app.module.ts

import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { ErrorHandlerInterceptor } from './blocks/interceptor/errorhandler.interceptor';
@NgModule({
  imports: [
    ...
    HttpClientModule
  declarations: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorHandlerInterceptor,
      multi: true
    }
  ],
  bootstrap: [MainComponent]
})

errorhandler.interceptor.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Hello');
    return next.handle(request);
  }
}

If you want to see the full code you can check my github

If I understood correctly, the console should display 'Hello' each time the interceptor is reached. But when I try to reached a non-existent url the console do not display 'Hello', just the error I want to handle...

Thanks for your help

2
  • I see no problem with your code, perhaps something else is wrong. Working stackblitz Commented Jan 21, 2019 at 12:53
  • The interceptor works well when I send a get request.I misunderstood how it works. Thanks a lot! Commented Jan 21, 2019 at 14:09

1 Answer 1

1

The interceptor is used to handle outgoing requests. Let's say you use the HttpClient to make a get request. Then it will go through the interceptor. Trying to navigate to a non-existing route is not catched by the interceptor.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for notice that's used for outgoing requests. Everything works fine!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.