Home > Back-end >  Is there any way to route to error page whenever error occurs in http api in angular?
Is there any way to route to error page whenever error occurs in http api in angular?

Time:10-19

I have 50 http api's in my application. I want to route to a page when error message or error occurs in an api i don't want to go to all service and add routing there i want to do it dynamically and simple? Any idea?

CodePudding user response:

Yes, you can use Http Interceptor to implement that.

Http Interceptor is standing between the client-side and the server-side and it catches every request and every response between.

So, you can catch the HTTP Response errors and navigate the user, something like:

@Injectable()
export class AuthInterceptorService implements HttpInterceptor {

  constructor(private router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any> | any> {
    return next.handle(req).pipe(
      tap(event => {
        // catch the success response
      }, err => {
           // navigate in case of errors
           this.router.navigate(['/error-page'])
      })
    );
  }

}
  • Related