how to throw observable error in angular http interceptor

前端 未结 3 1161
慢半拍i
慢半拍i 2020-12-19 04:04

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

相关标签:
3条回答
  • 2020-12-19 04:44

    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;
      );
    
    0 讨论(0)
  • 2020-12-19 04:45

    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;
        );
    
    0 讨论(0)
  • 2020-12-19 04:59

    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);
        }
    
    0 讨论(0)
提交回复
热议问题