2017-04-25 44 views
0

我有一个简单的任务。比方说,该用户可以添加一个新闻的形式有两个领域,标题和内容。标题字段必须填写。我可以检查它在客户端,而且在服务器端,例如:什么是处理Node js到Angular 2错误的正确方法?

news.js

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

这个错误可以在主app.js

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

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

,我想逮住在客户端捕获它:

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

如何做到这一点?我应该在服务器端发送给客户端? resp.status不起作用,因为我想要。这可能是更好的解决方案吗?

问候

回答

0

一般来说你的API应该返回一些错误代码(数字或字符串,它并不重要),以及您的角度前端应该处理的错误代码。

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'); 
    } 
}) 

然后在客户端上:

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 
     } 
    }) 
相关问题