I'm trying to make a global error interceptor so that on each and every error it would redirect to main page with error=true
query parameter. Somehow it catches the error, logs it but doesn't redirect. What am I doing wrong?
HttpErrorInterceptor:
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
errorMsg = `Error: ${error.error.message}`;
} else {
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
const urlParams = new URLSearchParams(window.location.search);
this.router.navigate(['main'], {queryParams: {error: true, sesskey: urlParams.get('sesskey')}});
console.log(errorMsg);
return throwError(errorMsg);
})
)
}
}
app.module.ts:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: HttpErrorInterceptor,
multi: true
},
I think this is working, how did you test it
for me it works like this
export class AppComponent {
constructor(private http: HttpClient) {
this.getData();
}
getData() {
const url = 'Fake url';
return this.http.get(url).subscribe();
}
}