2

I am trying to pass errors from my API to the Angular 4 application. The problem is that on the angular side I do not see proper error message:

Web Api error is generated like this:

        throw new HttpResponseException(
            new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Headers = {{"errorMessage", "Message in header"}},
                Content = new StringContent("Message in body")
            }
        );

My angular code is something like:

    return this._http.get<IMyObj[]>(this._serviceUrl)
      .do(this.handleSuccessResponse)
      .catch(this.handleErrorResponse);

    protected handleErrorResponse(err: HttpErrorResponse) {
        console.info(err);
        // some logic based on code
    }

The problem is that if I check err it's "error" property is null, message is "Response failed for url" and no custom header, however on the network tab in the browser I can see my custom header with error as well as error in body. How do I access any of this messages from my angular app?

2 Answers 2

3

My error handler looks like this:

private handleError(err: HttpErrorResponse) {
    // in a real world app, we may send the server to some remote logging infrastructure
    // instead of just logging it to the console
    let errorMessage = '';
    if (err.error instanceof Error) {
        // A client-side or network error occurred. Handle it accordingly.
        errorMessage = `An error occurred: ${err.error.message}`;
    } else {
        // The backend returned an unsuccessful response code.
        // The response body may contain clues as to what went wrong,
        errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
    }
    console.error(errorMessage);
    return Observable.throw(errorMessage);
}

Notice that it uses the status and message properties, not the error property.

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

6 Comments

In my client side logic I am actually having a switch on the status and for each status code I am doing something different. The problem is that the err.message is "Http failure response for localhost:56219/api/v1/test: 400 Bad Request", but in network tab in the response body I can see "Message in body" as well as I can see my custom header. My question is how do I access response body (or custom header) in my error handler.
Have you seen this: github.com/angular/angular/pull/18466 It says it's fixed.
Could be very basic question, but how do I update only angular to the version that has this fix? I tried bulk update but having issues after that: angular/core common and zone.js are getting as unmet dependencies.
After updating angular error property now has the body
@DeborahK how do we recognize in this example. what's client side error and what's server side error ? if the error is instanceof Error that it's client side? could you add some more code of how you use it on real app, I mean how you are invoking this handleError method .. Thanks Deborah!
|
0

You can Try this.

In this I am passing a search value. You can even try without that.

//Service.ts

import {catchError, map, tap } from 'rxjs/operators';
import {throwError} from 'rxjs';
import { HttpClient, HttpErrorResponse} from '@angular/common/http';

private employeeUrl="https://api.employee.new/dept/value.json?search=city:"
getdata(selectedtype): Observable<employee[]> {
return this.http.get<employee[]>(this.employeeUrl+selectedtype)
      .pipe(
  catchError(this.errorHandler)); 
}

errorHandler(error: HttpErrorResponse)
{
return throwError(error.message || 'Server Error')
}


//employeecomponent.ts

employeedata:any=[];
public errorMsg;
ngOnInit(){
this.dataService.getdata(this.search).subscribe(data =>this.employeedata=data,
                            error =>this.errorMsg=error);
}

//last you can bind it in the Html file

//employeecomponent.html

<h3>errorMsg</h3>

Comments

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.