Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda