0

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

4
  • Probably because .catch only runs when there IS an error. Commented Jan 8, 2016 at 16:35
  • i see.. aside from .catch what else can I use to get the desired effect? Commented Jan 8, 2016 at 16:44
  • 1
    use .then to handle the success, and .catch for errors. Commented Jan 8, 2016 at 16:45
  • Read up on Promises for Knex. Commented Jan 9, 2016 at 12:19

2 Answers 2

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.