Angular 2 Promise throw error

11,684

Solution 1

You are swallow the error in catch, you can still have a catch clause to transform the error but you need to return a rejected Promise from it. Something like that:

  let httpPromiseMock  = new Promise((resolve, reject)=> {
    reject('400 error');
  });

 httpPromiseMock
 .then(x=> {console.log(x); return x*2;})
 .catch(x=> Promise.reject(`my error is ${x}`))
 .then(x=>console.log('good',x), 
    err=>console.log('bad', err));

Solution 2

Should i throw something on the service so the code goes to the error start in case i get a 400+ status code?

Yes, because right now, your catch statement of the service is swallowing the error.

You could also get rid of the catch statement there, but you'll have to remember to add one in every piece of code that uses addContact.

Share:
11,684
Pacuraru Daniel
Author by

Pacuraru Daniel

Updated on July 13, 2022

Comments

  • Pacuraru Daniel
    Pacuraru Daniel almost 2 years

    I am trying to make a service that handles contacts in Angular 2. This is what i got so far.

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    
    import 'rxjs/add/operator/toPromise';
    
    @Injectable()
    export class ContactsService {
    
      constructor(private http: Http) { }
    
      addContact(contact): Promise<any> {
        return this.http
          .post('http://localhost:8000/contacts', contact)
          .toPromise()
          .then(response => response.json())
          .catch(error => error.json());
      }
    }
    

    Now the service works fine, if i get a 400+ status code on the response, the code goes to the catch stare, if it's 200 code it goes to then state and returns the response.

    But when i use it inside a component, it goes to then state no matter if the respone is ok or not.

    addingContact() {
      this.contactsService
        .addContact(this.user)
        .then(
          (contactx) => { console.log('THEN = ' + JSON.stringify(contactx)); },
          (err) => { console.log('CATCH = ' + JSON.stringify(err)); }
        );
    }
    

    Is there something i'm missing, should i throw something on the service so the code goes to the error start incase i get a 400+ status code ?

    Thank you in advance, Daniel!