weixin_33728708 2016-01-08 16:34 采纳率: 0%
浏览 27

Node.js错误处理

I am building an app using node.js and knex for the ORM. I want my insert command to send either a success or error response, but it is not working for some reason:

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

The code as is does NOT console.log out the error nor lack of error.

Note - the res.send(200) should go back to my client side to alert the client the request was successful.

Can someone help? Thanks in advance!!

  • 写回答

2条回答 默认 最新

  • weixin_33724059 2016-01-09 11:46
    关注

    Promises will either trigger your then function or the catch function. Not both. Handling the success case happens in the then function, handling the error case happens in the catch function.

    To demonstrate with your code:

    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);
    });
    
    评论

报告相同问题?