Not able to show error message in status 200 response

Viewed 879

I am trying to log message from backend where if I give wrong otp number it will throw status as 200ok and with error message in response body.

enter image description here

I want to log that error message ErrorMsg so that I can use it in some alert.

But in my case I am getting message which I have written in HttpErrorResponse in service

// Handle errors
  handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      console.error('An error occurred:', error.error.message);
    } else {
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    return throwError(
      'Something bad happened; please try again later.');
  }

So I am getting Something bad happened; please try again later in error response. How I can change this to the one I am getting in POSTMAN ?

Service login:-

//POST API for Login
  loginForm(data: any): Observable<RootObject> {
    return this.http
      .post<RootObject>(`${environment.baseUrl}/VerifyMobileOTP`, data, this.httpOptions)
      .pipe(
        tap((resp: RootObject) => this.setUser(resp.Result as Result)),
        catchError(this.handleError)
      );
  }

  setUser(resp: Result) {
    this.storageService.secureStorage.setItem('username', JSON.stringify(resp.username));
    this.storageService.secureStorage.setItem('access_token', JSON.stringify(resp.access_token));
    this.router.navigate(['/home']);
  }

Model:-

export interface Result {
    access_token: string;
    username: string;
}

export interface RootObject {
    IsSuccess: boolean;
    ErrorMsg: string;
    Result: Result;
    ErrorCode?: any;
}

Login Component :-

   login() {
        this.loading = true;
        var number = this.loginForm.value[Object.keys(this.loginForm.value)[0]]
        this.otp = this.otpForm.value[Object.keys(this.otpForm.value)[0]]
        console.log(number, this.otp);
        var loggedin = { "MobileNumber": number, "OTP": this.otp }
        // call login api
        this.authService.loginForm(loggedin).subscribe(response => {
          console.log(response);
          this.errorLogin = response.ErrorMsg;
          console.log(this.errorLogin);  // ------> How to console 200ok response error ?
          this.loading = false;
        }, error => {
          this.loading = false;
          this.status = error;
          console.log(error)  // ------------>>>> this error msg I am receiving from httperrorresponse
        });
      }

EDIT:-

On consoling response I am getting value from Result model only and not the value from model RootObject which content ErrorMsg and IsSucess values

{
    access_token: fdgfefeWD45dfdS ....;
    username: test@wren.com;
}
2 Answers

SOLVED !!

I was not passing entire response. Only Result I was passing. So I passed all RootObjects in service.

.post<RootObject>(`${environment.baseUrl}/VerifyMobileOTP`, data, this.httpOptions)
      .pipe(
        // tap((resp: RootObject) => this.setUser(resp.Result as Result)),
        catchError(this.handleError)
      );

And in component:

this.authService.loginForm(loggedin).subscribe(response => {
      if (response.IsSuccess == true) {
        this.authService.setUser(response.Result); // ---->calling localstorage set func here isntead of tap in service.
      }
      else {
        this.errorLogin = response.ErrorMsg; // loggin error with 200OK status
        this.loading = false;
      }

Your backend server is giving a 200 OK response with error JSON.

Now an Observable treats a 200 response as success.

observable$.subscribe(
  () => {}, // next handler (for success)
  (err: HttpErrorResponse) => {} // error handler
)

When your server responds 200 or 201 or 202 or 2xx (2 anything) the observable will call the success handler. This is not what you want, you need it to call the error handler. To do this, make sure you server gives a 4xx (e.g. 400 401 404) or 5xx (e.g. 500) response. Then Angular will auto call the error handler, which is what you need.

EDIT

Further to your comment, you could do this but its not good practice:

observable$.subscribe(
  (res: any) => {
    if (res.IsSuccess === false && res.ErrorMsg != null) {
      // do error stuff here
    } else {
      // success here
    }
  }, // next handler (for success)
  (err: HttpErrorResponse) => {} // error handler
)
Related