1

I recently started using Angular 2 and quickly discovered that when utilizing the HTTP client that a return code of 404 from the server ends up rejecting the promise.

Here's the code I have in my service:

  export class CalculatorService {

  private _serviceUrl = 'http://localhost:3000';
  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(private http: Http) { }

  getCode(request: CalculatorRequest) {
    return this.http.post(this._serviceUrl, JSON.stringify(request), {headers: this.headers})
        .toPromise()
        .then(response => response.json() as CalculatorResponse)
        .catch(this.handleError);
  }

  private handleError(error): Promise<any> {
    const errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server Error : Service Unavailable';

    if (errMsg != null) {
      return Promise.reject(errMsg);
    }
  }
}

Unfortunately, instead of resolving the promise, my handleError method is called as the 404 causes a rejection.

Is there a straightforward way to resolve a request with a return code of 404?

Thanks!

4
  • 1
    I'm sorry this may not be the answer you are looking for, however have you considered using observables? They allow for a better (in my opinion) way of handling errors (and responses) Commented Aug 7, 2017 at 16:37
  • No worries! I am very new at utilizing Angular 2 and have only briefly looked at Observables. I will definitely be looking into them further as they appear to be extremely powerful. Commented Aug 7, 2017 at 16:40
  • 1
    I would offer an observable solution, however people returning to this question in the future will be looking for a way to do it with promises. This answer deals with how to do this in an observable if you want to switch and do it that way! Commented Aug 7, 2017 at 16:43
  • It's not clear what the problem is. Yes, it causes a rejection. And yes, it should can be handled in catch - like any other expected error. If only thing you do in catch is rejection, this will result in rejected promise when there's http error. Commented Aug 7, 2017 at 17:40

0

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.