0
votes

Background

We are migrating an AngularJS app to newest Angular version. We process http requests by ALWAYS receiving status code 200, if there is an error, we still get status code 200 (excluding 404 - 500, and errors regarding the actual server or user connection). For example, if User Token expires and we make a request, we get a status code 200 with a body of errorCode: number, message: string. This will not change.

Problem

Using the same example about the token, all the code examples I've seen regarding Interceptors processing the invalid token issue and refresh it in the CatchError of the observable:

return next.handle(request).pipe(
  map((event: HttpEvent<any>) => {
    <Process Response, and errors in my project>
  }),
  catchError((error: HttpErrorResponse) => {
    <Process Invalid Token in code examples>
  }),
);

This Code examples are not working for me because as I said, in my project we process the errors in the response section, not catchError. When we get an Invalid Token issue, we refresh the token and retry the original call that failed.

It's a lot easier if we process in catchError because it's expecting an observable and will handle the Observable by it's own, but in the response section, it's not expecting an observable... I managed to make the call to refresh the token in the response section and retry the http call that had the error but when I try to return the response that worked, it never reached the scope of the first call.

Any ideas how I can make the refresh call and retry the first http call out of the catchError?

1
you can get response body by event.body.errorCode. and then do your own logic. like in my case i was getting status SUCCESS or FAILURE in response body. i was getting Failure in my interceptor and was showing message. and in case of SUCCESS, i was assigning data in subscribe method.Farhat Zaman
It's very unclear what are you trying to solve. Your backend always returns 200 but you're using catchError and there you have a problem that it expects an Observable somewhere?martin
@martin Hi Martin, I know is confusing, even for me it's hard to explain because the way backend handles errors I believe it's not a good practice. What I learned is that when you use catchError in interceptors, you can return an observable. The answer below from Ivan I think it fixes my issue, I try to refresh token and retry the http call, if I'm able to return that http call observable in the catch (like all the examples do), it will be fixed but it's not my case, I will try Ivan solution, hope it works, also I hope I could clear it out, thanks again for the helpLuigi Cordoba Granera

1 Answers

2
votes

All you need to do in this case is parse the body of the response in the interceptor and return

if (res.body.includes(...)) {

           throw of(new HttpErrorResponse({status: 500, statusText: 'Simulated erorr'}));

}