Home > Net >  Angular, HttpClient, subscribe do not catch the error when 401
Angular, HttpClient, subscribe do not catch the error when 401

Time:04-29

I have something strange with my code. I have this in my service, very basic, a simple httpClient get... When the API returns as status 401, I am expecting that it goes into the error... But it does not. In my console, I only have the 'complete'. When the API returns the status 200, it does well in the 'next' Any Idea?

import { HttpClient } from '@angular/common/http';
...
  constructor(
    private httpClient: HttpClient,
    private configService: ConfigService
  ) {}

  getUserDetails() {
    console.log('AuthService.getUserDetails');
    return this.httpClient
      .get<UserDetails>(this.configService.getModuleCoreAPi('users.details'))
      .subscribe({
        next: (ud) => {
          console.log('next', ud);
          this.userInfos.next(ud);
        },
        error: (error) => {
          console.log('error', error);
        },
        complete: () => console.log('complete'),
      });
  }
...

UPDATE 1: This is not working either

  getUserDetails() {
    console.log('AuthService.getUserDetails');
    this.httpClient
      .get<UserDetails>(this.configService.getModuleCoreAPi('users.details'))
      .pipe(
        catchError((err) => {
          throw 'error in source. Details: '   err;
        })
      )
      .subscribe(
        (ud) => {
          console.log('next', ud);
          this.userInfos.next(ud);
        },
        (error) => {
          console.log(error);
        }
      );
  }

nor

  getUserDetails() {
    console.log('AuthService.getUserDetails');
    this.httpClient
      .get<UserDetails>(this.configService.getModuleCoreAPi('users.details'))
      .pipe(
        catchError(err => {
          throw 'error in source. Details: '   err;
        })
      )
      .subscribe({
        next: (ud) => {
          console.log('next', ud);
          this.userInfos.next(ud);
        },
        error: (err) => console.log(err),
      });
  }

Update 2 If I force the API to return the 500 status code, it passes as expected into the error

CodePudding user response:

I usually use rxjs catchError() for this.

this.httpClient
  .get<UserDetails>(this.configService.getModuleCoreAPi('users.details'))
  .pipe(catchError((error) => console.log(error))
  .subscribe((ud) => this.userInfos.next(ud));

CodePudding user response:

Well, I forgot about the interceptor that is enabled and catching the 401 status code... Need to rest ;)

CodePudding user response:

you are destructuring the first parameter returned from "subscribe" method. Remove the first curly braces:

.subscribe(
        (ud) => {
          console.log('next', ud);
          this.userInfos.next(ud);
        },
        (error) => {
          console.log('error', error);
        },
        () => console.log('complete')
      );
  • Related