Tuesday, 25 April 2017

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



via Michal Bialek

No comments:

Post a Comment