简体   繁体   中英

Angular 8 Interceptors - How to process response in status 200

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?

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'}));

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM