处理从节点j到Angular 2的错误的正确方法是什么?

时间:2017-04-25 11:33:35

标签: node.js angular

我有一个简单的任务。可以说,该用户可以在包含两个字段(标题和内容)的表单中添加新闻。必须填写标题字段。我可以在客户端检查它,但也可以在服务器端检查它,例如:

news.js

Apps

可以在主app.js

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

我想在客户端抓住它:

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

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

怎么做?我应该在服务器端向客户端发送什么? resp.status无法正常工作。这可能是一个更好的解决方案吗?

此致

1 个答案:

答案 0 :(得分: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
        }
    })