How to read Custom error message from backend in Angular 4/2

Viewed 6803
API

add(data) {
 return this.httpClient.post<any>('/api/v3/templates', data);
}

Observable

this.templateService.add(obj)

.subscribe(
 (response) => { 
  console.log(reposne)
 },
(error) => {
 console.log(error)
 }
);

My Post API gives back a error with some Message in response as Name Already Exists But i am not able to get that in error Object which is printed to console

The object which is printed is
{
    error:null
    headers:HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, 
    lazyInit: ƒ}
    message:"Http failure response for http://localhost/api/v3/templates: 
400 Bad Request"
    name:"HttpErrorResponse"
    ok:false
    status:400
    statusText:"Bad Request"
    url:"http://localhost/api/v3/templates"

}

how can I get the message that I am getting in response as my error object doesn't have that response body.

3 Answers

In Observable there are three options.

  • Next - which you subscribed to get the data
  • Error - Its the next function you passed to the subscribe method. It contains the error status code and mostly http error like error in connection, bad request.
  • finally - its execute any how after all.

there are others too like map, debounce etc.

  this.templateService.add(obj)
    .subscribe(
      (response) => {  // this is the next and hold the response
        console.log(response)
      },
      (error) => { // this is the error
        console.log(error)
      },
      (finall) => { // this is final and execute alwasys
        console.log('this is the final piece of code to execute')
      }
    );

I think you your case the error might not coming in http standard and might be coming in subscribe.

So check if the customized message is coming in next rather as an error.

Related