Home > Software design >  How to redirect an HttpErrorResponse to the success callback using an interceptor?
How to redirect an HttpErrorResponse to the success callback using an interceptor?

Time:01-29

I have successfully programmed HttpInterceptor which has

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<any> {

And it has proper catchError and throwError

catchError((error: HttpErrorResponse) => {
   return throwError(error)
})

Everything is working fine

But I want to convert this to a non error HttpEvent so that I can receive both success and error inside the same callback of the HttpClient response how do I achieve that?

CodePudding user response:

If you want to receive the error-response in the same callback as the success-response you have to change the value of the status-property of the HttpResponse to 2xx. Otherwise it will still enter the error-callback. At the same time you can assign the original error-object to the body-property of your response:

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request)
        .pipe(
        catchError((error: HttpErrorResponse) =>
            of(new HttpResponse({
                body: error,
                status: 200, // if the status is not 2xx, it will enter the error-callback
                statusText: 'OK'
            }))
        )
    );
}

Note of caution: Modifying the status code of an http-response is usually not considered good practice, yet sometimes it can be a workaround.

  • Related