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

3

4
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.

Outvote answered 20/9, 2017 at 14:15 Comment(3)
This response says its a bad request ` status:400 statusText:"Bad Request"`Tarkington
I am getting a response in text with this error which is not in the error object and the https statusText is the property contains the text of the response status, such as "OK" or "Not Found"/ BadRequet.Outvote
@atulmishra, have you found solution for this one. I am also trying to send custom error message from server but can't receive it when using HttpClient. However same thing worgs perfectly when I use older HttpDylane
A
1

The error returned is normally an instance of HttpErrorResponse, with an error property containing the wrapped error (client or server)

https://angular.io/guide/http#getting-error-details

So normally you should be able to handle the error like this.

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

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an ErrorObservable with a user-facing error message
  return new ErrorObservable(
    'Something bad happened; please try again later.');
};

If the error property is null this could be because the server does not return anything. Did you check using postman or some other tool that your server returns the appropriate response?

Ayotte answered 8/4, 2018 at 7:45 Comment(0)
T
0

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.

Tarkington answered 20/9, 2017 at 14:30 Comment(5)
added the code, also fount that in the console.log the spelling of response is wrong, you can correct thatTarkington
Still not getting and I was doing the same thingOutvote
@atulmishra Did you find an answer to this question yet?Matrass
@Matrass Nope still didnt getOutvote
Passing multiple arguments is deprecated since RxJS 6.4: rxjs.dev/deprecations/subscribe-arguments. Rather, an object with next, error, complete properties with function values should be passed as argument.Electrocardiograph
C
0

You can use a typed response:

On your error notification type you could have something like:

err =>  {
        this.localErrorResponse = err as ErrorResponse;
        this.message= this.localErrorResponse.message;
      }

before, in your class:

import { ErrorResponse } from './error-response';
...
localErrorResponse: ErrorResponse;
message: string;

and then, your ErrorResponse can be like:

import { HttpHeaders} from './http-headers';

export class ErrorResponse{
  error: any;
  headers: HttpHeaders;
  message: string;
  name: string;
  ok: boolean;
  status: number;
  statusText: string;
  url: string;
}

and class HttpHeaders

export class HttpHeaders {
  normalizedNames: any;
  lazyUpdate: any;
  lazyInit: any;
}

then you can map some other variables, as message (this.message)

Chink answered 11/4, 2018 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.