0

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.

1
  • Just make sure your backend returns the correct status Commented Aug 29, 2018 at 11:04

1 Answer 1

1

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;
        }));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.