I followed the last hours a tutorial about jwt refresh tokens but it seems that the code is a bit older and there were some changes. So I build an interceptor which got a problem with the Observable and I don't know how to fix it.
The Error is:
"Function lacks ending return statement and return type does not include 'undefined'"
and I know it shows up because my Observable has no specific return.
My Code:
intercept(request : HttpRequest<any>, next : HttpHandler): Observable<HttpEvent<any>>
{
// Check if the user is logging in for the first time
return next.handle(this.attachTokenToRequest(request)).pipe(
tap((event : HttpEvent<any>) => {
if(event instanceof HttpResponse)
{
console.log("Success");
}
}),
catchError((err) : Observable<any> => { //Here comes the error message
if(err instanceof HttpErrorResponse) {
switch((<HttpErrorResponse>err).status)
{
case 401:
console.log("Token expired. Attempting refresh ...");
return this.handleHttpResponseError(request, next);
case 400:
return <any>this.acct.logout();
}
} else
{
return throwError(this.handleError);
}
//I think here should be a return but I don't know which kind, tried already a few ones
})
);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I also can show you the original Code of the tutorial, that's the link:
CodePudding user response:
Catches errors on the observable to be handled by returning a new observable or throwing an error. catchError
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Check if the user is logging in for the first time
return next.handle(this.attachTokenToRequest(request)).pipe(
tap((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
console.log('Success');
}
}),
catchError((err): Observable<any> => {
if (err instanceof HttpErrorResponse && err.status === 401) return this.handleHttpResponseError(request, next);
/**
* I think the problem is here, the logout function does not return an observable and you can do like this
*/
if (err instanceof HttpErrorResponse && err.status === 400) this.acct.logout();
return throwError(this.handleError);
}),
);
}