I have an Http Interceptor (Angular 7) that catches errors. Is it possible to catch the error and based on some contidition, returns a success instead of the error? My current code.
export class RequestInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError( response => {
if(someCondition) {
//return something that won't throw an error
}
return of(response)
})
)
}
}
After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.
HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.
Yes, you can have multiple angular interceptors by changing the value of multi to true.
HttpErrorResponselink A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which occurred during the parsing of the response.
You need to return an Observable<HttpEvent<any>>
object. You can achieve that by making another request using next.handle(newReq)
For example, if you want to add a Bearer authorization header if the error is 401, you can do like that
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError( response => {
if(response.status === 401) {
return next.handle(request.clone({
setHeaders: { "Authorization": `Bearer ${token}` }
}));
}
return throwError(() => new Error(response));
})
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With