1

I'm trying to capture http status codes in angular in service which calls a backend service, i'm facing issues as i see status 204 , but when logging angular show status null, here is what i'm doing in my service:

return this.http.get<JSON>(mybackendsserviceurl)
      .do(res => {
      })
      .catch(res => {
        return this.handleError(res);
      });
  }

  private handleError(err: HttpErrorResponse) {
    console.log(err.message);
    return Observable.throw(err.message);
  }

How to catch different errors from backend service, like 204,403,404,500...etc and display a user friendly message for each error? my frontend is calling the service from API gateway and i'm setting the errors in Response Integrations.

1
  • Where do you log the status code? Commented Aug 30, 2018 at 18:10

1 Answer 1

2

To handle different status codes just check them:

this.http.get<JSON>(<URL>)
    .subscribe( 
        res => console.log(res), 
        err => {
            console.error(err);
            this.handleError(err);
        });


private handleError(err: HttpErrorResponse) {
    if( err.status == 500 ) {

        return Observable.throw(new Error(<YOUR USERFRIENDLY MESSAGE>));

    } else if( err.status == 400 ) {

        return Observable.throw(new Error(<YOUR MESSAGE>));
    }

    // you can also catch all errors of a group like this
    else if( err.status < 500 && err.status >= 400 ) {

        return Observable.throw(new Error(<CLIENT ERROR MESSAGE>));
    }
}

In your UI you can handle the Observable and of course, show a nice dialog with the error message.

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

10 Comments

When adding this in the HandleError, none of console log comes up private handleError(err: HttpErrorResponse) { if( err.status == 500 ) { console.log(err.status,"500 from servce"); return Observable.throw(new Error(<YOUR USERFRIENDLY MESSAGE>)); } if( err.status == 400 ) { return Observable.throw(newError(<YOUR MESSAGE>)); } }
how do you log errors? Do you produce an HTTP error and is the .catch executed?
console.log(err.message); prints: Http failure response for (unknown url): 0 Unknown Error none of the status set above is executed
You have probably a problem with CORS. Try the same page with Google Chrome and see, what the JS console writes.
Yes, i'm on chrome and the console has following errors: OPTIONS 403 () requestURL then Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
|

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.