2016-01-08 183 views
0

我在为ORM构建一个使用node.js和knex的应用程序。我希望我的INSERT命令发送成功或错误的反应,但它不工作由于某些原因:Node.js错误处理

knex('reports').insert({ 
    reportid: reportId, 
    created_at: currentDate 
}).then().catch(function(error) { 
    if(error) { 
     console.log("error!!!: " + error) 
     res.send(400, error); 
    } else { 
     console.log('no error'); 
     res.send(200); 
    } 
}); 

代码原样不CONSOLE.LOG出了错误,也没有错误。

注 - res.send(200)应该返回到我的客户端以提醒客户端请求已成功。

有人可以帮忙吗?提前致谢!!

+0

可能是因为.catch onl y在出现错误时运行。 –

+0

我明白了..除了'.catch'我还能用什么来获得理想的效果? –

+1

然后使用。然后处理成功,并收集错误。 –

回答

2

承诺将触发您的then函数或catch函数。不是都。处理成功案例发生在then函数中,处理错误案例发生在catch函数中。

要与您的代码演示:

knex('reports').insert({ 
    reportid: reportId, 
    created_at: currentDate 
}).then(function(data) { 
    console.log('no error'); 
    res.send(200); 
}).catch(function(error) { 
    console.log("error!!!: " + error) 
    res.send(400, error); 
});