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

176
Visualizações
What is a proper way to handle errors from Node js to Angular 2?

I have a simple task. Lets say, that user can add a news in a form which has two fields, title and content. Title field must be filled. I can check it on client side but also on server side, for example:

news.js

var _this = module.exports = {
   add: (news) => {
      return new Promise((resolve, reject) => {
            if(!news.title)
                reject('Title must be filled!')
            //rest of code
      })
   }
}

this error can be catched in main app.js

app.post('/add_news', (req, resp) => {
   var news = req.body.data;

   _news.add(news).then(result => {
       //send success
   }).catch(err => {
       //send error
   })
})

and I want to catch it on client side:

this.newsService.add(news).subscribe(
   result => {
      //here ok
   }, 
   error => {
     //here errors
   })

How to do it? What should I send on server side to client? resp.status does not work as I want. Is it maybe a better solution?

Regards

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Generally your API should return some error code (number or string, it does not matter), and your angular frontend should handle that error code.

news.js

if (!news.title) {
    reject({statusCode: 404, errorCode: 'MISSING_TITLE'});
}

app.js

_news.add(news).then(result => {
    //send success
}).catch(err => {
    // process only errors with `statusCode` and `errorCode`
    if (err.statusCode && err.errorCode) {
        resp.status(err.statusCode);
        resp.json(err.errorCode);
    } else { // otherwise return generic error
        resp.status(500);
        resp.json('API_ERROR');
    }
})

Then on the client side:

this.newsService.add(news).subscribe(
    result => {
        //here ok
    }, 
    error => {
        if (error === 'MISSING_TITLE') {
            alert('Title field is required!'); // or modify the $scope to show some error message in your template
        } else {
            alert('An error occurred'); // fallback to general error message when some other message comes
        }
    })
over 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