Is it the right way of using the http interceptor like this?

I always return http 200 back and define my own error code. If using Promise, I could reject a response which contains customized error. How can I do it using Observable? I do it like this and it works, but is it a correct way?

My interceptor:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return next.handle(req).flatMap((event: any) => {
  if (event instanceof HttpResponse) {
    if (event.body.status) {
      if (event.body.status === 'NOK') {
        return Observable.throw(event.body);
      }
    }
  }
  return Observable.create(observer => observer.next(event));
})}

My provider:

return this.http.post(this.apiUrl + func, requestData, options).map(
  (response) => {
    //do something with the response
    return response;
  }).catch(this.handleErrorObservable);

private handleErrorObservable(error: Response | any) {
//console.error(error.message || error);
return Observable.throw(error.message || error);

}

My component:

if (form.valid) {
  this.auth.signIn(this.login).subscribe(val => {
    //console.log(val);
    this.navCtrl.setRoot('WebPage');
  }, err => console.log(err))
}

200 means success. Why aren’t you following the spirit of HTTP and returning 400 for errors, which incidentally will make this problem automatically go away?

1 Like

Thx for the advise rapropos. I wish I could. It’s an inherited project created two years ago and I am rewriting the front-end with the new ionic framework. Changing the back-end isn’t feasible at this stage.
You’re an expert here. Do you see any issues regarding the way how I use the observable?