1

I don't get anything in response if an error is thrown from WEB API. but get a response in case of success and debugger hits.

I just want to receive an error response and debugger should be hit always whether an error is thrown or a success message is sent from the web API.

   this.dataService.post(this.defaultURL + "changepassword", myObject ).subscribe(result => {
          debugger // this is not hitting in case of error. 
          const res = result;
        });

    // Data Service contain HTTP post method. and i tested all three shown below. 
    // post 1 
    post(url: string, body: string): Observable<any> {
      return this.httpClient.post<Response>(url, body);
    }

    // post 2
      post(url: string, body): Observable<any> {
        return this.http.post<Response>(url, body).pipe(catchError(error => {
          return this.handleError(of(error.error));
        } ));
      }

    // post 3
    post(url: string, body): Observable<any> {
      return this.httpClient.post<Response>(url, body).pipe(catchError(error => {
      retry(1),
      catchError(this.handleError)
         return this.handleError(of(error.error));
      } ));
    } 


    handleError(error) {
      debugger

      let errorMessage = '';
      if (error.error instanceof ErrorEvent) {
          // client-side error
          errorMessage = `Error: ${error.error.message}`;
      } else {
          // server-side error
          errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
      }
      console.log(errorMessage);
      return throwError(errorMessage);
    }

API

[HttpPost("changepassword")]
public IActionResult ChangePassword([FromBody] ChangePasswordViewModel changePasswordModel)
{        
   if (_identityAdapter.ChangePassword( changePasswordModel.OldPassword, changePasswordModel.NewPassword))
         return Ok("Password has been updated successfully");
   return BadRequest();
}

1 Answer 1

2

Here's what you can do to handle your error response easily.

Observables objects in angular have the following observers:

  1. Next: Required. A handler for each delivered value. Called zero or more times after execution starts.
  2. Error: Optional. A handler for an error notification. An error halts execution of the observable instance.
  3. Complete: Optional. A handler for the execution-complete notification. Delayed values can continue to be delivered to the next handler after execution is complete.

Let's suppose you have one post service.

Service.ts

  add(offer: any): Observable<any> {
     return this.httpClient.post(API_URL + 'offers', offer);
  }

Component.ts

    this.service.add(offerToSend).subscribe(
      next => {
           // Code 
      },
      error => {
        //Catching error
      },
      () => {
        //Success Response
      }
  );

UPDATE:

Based on your comments, here's what you can do:

Service.ts

add(object: any): Observable<any> {
  return this.httpClient
    .post(API_URL + 'notifications', object).catch(this.handleError);
}

private handleError(error: Response | any) {
  console.error('NotificationService::handleError', error);
  return Observable.throw(error);
}

Using the above method in your service.ts will allow you to handle errors in service instead of components

Sign up to request clarification or add additional context in comments.

12 Comments

yeah, it works now, but I want the above add method to handle the errors for me, as I would call it in different components. and I would keep it in a centralized service by the name post.
basically i do not want to write an error method in each web API call.
@NaveedUllahJlani Please check the update, add a private method to the service in which it handles the errors
a red line showing below .catch, and error is "Property 'catch' does not exist on type 'Observable<Object>'"
Where are you importing the Observable from?
|

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.