简体   繁体   中英

Node.js error handling

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!!

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

You should handle the positive flow within the .then part:

then()
{
        console.log('no error');
        res.send(200);
    }

Also it's not consider a good practice to mix DB code with HTTP related logic as they probably should reside in different layers/components, see best practice number 4 here: http://goldbergyoni.com/checklist-best-practices-of-node-js-error-handling/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM