15

I tried to throw an observable error in the interceptor and then handles this error. but I can't. When success is false, I can also receive successful subscribe.

I tried to return a value again in next.handle(restReq). But I failed and did not subscribe to anything

restApi return like this

{
  "success": false,
  "data": {
    "name": "Bad Request",
    "message": "123",
    "code": 0,
    "status": 400,
    "type": "yii\\web\\BadRequestHttpException"
  }
}

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/internal/Observable';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private sessionUrl = '/wechat/session';

  constructor(
    private http: HttpClient
  ) { }

  getSession(): Observable<any> {
    return this.http.post<any>(this.sessionUrl, {});
  }
}

auth.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '@core/services/auth.service';
import { interval } from 'rxjs/internal/observable/interval';
import { switchMap, take } from 'rxjs/operators';

@Component({
 selector: 'app-auth',
 templateUrl: './auth.component.html',
 styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {
  constructor(
    private authService: AuthService
  ) { }

  ngOnInit(): void {
    this.authService.getLoginQrcode()
      .subscribe(
        data => console.log(data),
        error => console.log(error);
  }
}

http-interceptor.ts

import { Injectable } from '@angular/core';
import {
  HttpErrorResponse,
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from '@angular/common/http';

import { Observable } from 'rxjs';

@Injectable()
export class RestInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let baseUrl = environment.baseUrl + '/' + environment.version;
    let headers = req.headers;
    const restReq = req.clone({
      headers,
      withCredentials: true
    });

    return next.handle(restReq);
  }
}
1
  • which http status is returned by your server when success is false? Commented May 4, 2018 at 20:01

4 Answers 4

17

Try doing this in your interceptor

return next.handle(request).map((event: HttpEvent<any>) => {
       if (event instanceof HttpResponse && event.body && !event.body.success) {
         throw new HttpErrorResponse({
                            error: 'your error',
                            headers: evt.headers,
                            status: 500,
                            statusText: 'Warning',
                            url: evt.url
                        });
       }
       return event;
    );
Sign up to request clarification or add additional context in comments.

Comments

1

You can add catch, and handle error

//....
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    constructor(private inj: Injector, private _router: Router) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        // Get the auth header from the service.
        const auth = this.inj.get(AuthService);
        const authToken = auth.getSessionData().accessToken || '';
        const duplicate = req.clone({headers: req.headers.set('Authorization', authToken)});
        return next.handle(duplicate).catch(this.handleError);
    }

    private handleError = (response: any) => {
// ....
        // Do messaging and error handling here
        return Observable.throw(response);
    }

1 Comment

This is the one most similar to what worked for me on Angular 10. throwing an actual error didn't work - but I needed to throwError(new HttpErrorResponse(....
0

Try doing this in your interceptor

return next.handle(request).map((event: HttpEvent<any>) => {
  if (event instanceof HttpResponse && !event.body.success) {
    throw new Error(event.body.message);
  }
  return event;
  );

1 Comment

if i throw error like this it works fine but prints "ERROR {responseData: {…}, responseCode: 401}" on console. how can i avoid this?
0

I think that this is a better way to throw an error in the chain:

  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    if (req.url.match(/.*url/)) {
      return throwError(
        () =>
          new HttpErrorResponse({
            error: 'your error',
            status: 403
          })
      );
    }
}

This way the error is propagated through the error interceptor chain.

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.