简体   繁体   中英

Angular6 handle http errors based on status code inside response block

My login service (written in Django), while user is unauthorized return {"message":{"password":["invalid user name or password !"]},"status":111} but status code returned by http request is 200, so request goes to success block instead of error block.

My question is there any way catch error in error block based on the status code return inside the response.

You need to create an interceptor. See how to create an interceptor here

In your interceptor you can do something like this. Intercept the response, check for your condition and throw error accordingly.

export class YourInterceptor implements HttpInterceptor{
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
              //check for your condition here, if true, return error as follows. This will run your error block.
                return Observable.throw(new HttpErrorResponse({status:401, statusText:"Error of auth"}));
        }
}

With Angular 6 and (rxjs 6) you can now do it this way

intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).pipe(tap((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) //Check if it is a response
            {
                if(your condition here) //hint: Use event object to get your response
                {
                     throwError('Your error')
                }
            }
            return event;
        }));
}

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