error handling - Angular 4.3 - HTTP Interceptor - refresh JWT token -
i need react (in interceptor class) on 403 forbidden http status (to obtain/refresh) jwt token , retry request fresh token.
in code below, when server return error response goes success callback (not error callback expect) , event typeof object (which useless in reaction on error response). event object looks this: {type:0}.
question:
-how handle httperrorresponse (403 forbidden) in httpinterceptor when need refresh accesstoken , retry http request?
import { httpinterceptor, httprequest, httpresponse, httphandler, httpevent } '@angular/common/http'; import 'rxjs/add/operator/map'; @injectable() class jwtinterceptor implements httpinterceptor { constructor(private tokenservice: tokenservice) {} intercept(req: httprequest<any>, next: httphandler): observable<httpevent<any>> { let myheaders = req.headers; if (this.tokenservice.accesstoken) { myheaders = myheaders.append('authorization',`${this.tokenservice.accesstoken.token_type} ${this.tokenservice.accesstoken.access_token}`) } const authreq = req.clone({headers: myheaders}); return next.handle(authreq).map((event: httpevent<any>) => { if (event instanceof httpresponse) { // success callback } }, (err: any) => { if (err instanceof httperrorresponse { if (err.status === 403) { // error callback this.tokenservice.obtainaccesstoken() } } }) .retry(1); } }
you need add catch
operator rxjs. error be, , can handle accordingly.
when error of status 0, means remote server down , connection not made.
take @ example logic:
this.http.request(url, options) .map((res: response) => res.json()) .catch((error: any) => { const err = error.json(); // refresh jwt if (err.status === 403) { // add token refresh logic here. } return observable.throw(err); });
in order refresh logic go through interceptor, need return invocation, , function should return observable
. example modifying original logic above:
this.http.request(url, options) .map((res: response) => res.json()) .catch((error: any) => { const err = error.json(); // refresh jwt if (err.status === 403) { // refreshtoken makes http call , returns observable. return this.refreshtoken(...); } return observable.throw(err); });
if want able retry original request, can pass original request data on refreshing token can make call again. example, refreshtoken
function like:
refreshtoken(url: stirng, options: requestoptionsargs, body: any, tokendata: any): observable<any> return this.post(`${this.url}/token/refresh`, tokendata) .flatmap((res: any) => { // retry original request return this.request(url, options, body); }); }
Comments
Post a Comment