Reputation: 2102
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.
Upvotes: 0
Views: 583
Reputation: 2225
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;
}));
}
Upvotes: 1