In my project I'm using Angular 15. Inside I'm using two interceptors "HttpRequestInterceptor" and "ErrorInterceptor". The HttpRequestInterceptor deletes the error status code and error message from server response, because when I switch off this interceptor - everything is OK. But I'm need this interceptor for add withCredentials: true to make browser include Cookie on the Request header (HttpOnly Cookie). I'm send test requests to http://httpstat.us/404 - so this is not because of CORS.
Please give me advice - how to handle this situation with this HttpRequestInterceptor?
HttpRequestInterceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class HttpRequestInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
withCredentials: true,
});
return next.handle(req);
}
}
and
ErrorInterceptor.ts
import { Injectable } from '@angular/core';
import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpErrorResponse} from '@angular/common/http';
import { catchError, Observable, throwError } from 'rxjs';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error) => {
if (error instanceof HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log('Error Event');
} else {
console.log(error);
switch (error.status) {
case 401: // Unautorized
console.log(error.statusText);
break;
case 403: // Forbidden
console.log(error.statusText);
break;
case 404: // Not found
console.log(error.statusText);
break;
case 503: // Server error
console.log(error.statusText);
break;
}
}
} else {
console.log('An error occurred');
}
return throwError(() => new Error(error.statusText));
})
);
}
}
and
interceptors.ts
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpRequestInterceptor } from './http.interceptor';
import { ErrorInterceptor } from './error.interceptor';
export const interceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: HttpRequestInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
];
Error browser log without codes
CodePudding user response:
This is my mistake. Adding this fix the code. Sometimes we need take rest and look on task from another angle :)
if (req.url.startsWith('http://localhost:8080/api')) {
req = req.clone({
withCredentials: true,
});
}