Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
Angular 2 Promise throw error

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!

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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));
about 4 years ago · Santiago Trujillo Denunciar

0

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.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda