Handling rejected promises in Express without crashing app

147 views Asked by At

I'm pretty new to express still and having some issues with rejected promises. To illustrate the issue I have a function using node pg-promise to query my database. Everything works fine if both entries exist, but if one does not it returns a rejected promise (as it is supposed to). My problem is what to do with the rejected promise. Right now my app crashes and logs the rejection.

I have error handling middleware that handles all errors by sending a response with the error message and status. This works fine for any other error I have thrown at it, but not rejected promises (which in fact never even reach it).

How can I handle rejected promises like these without my app crashing?

Here is my database function that returns the promise

 const transferColumnAmount = (fromTable, toTable, fromId, toId, column, amount) => {
    db.tx(t =>{
        return t.batch([
            t.one('UPDATE ${table:name} SET ${column:name} = ${column:name} + ${amount:csv} WHERE id = ${id:csv} RETURNING *', {
                table: fromTable,
                column: column,
                amount: -amount,
                id: fromId
            }),
            t.one('UPDATE ${table:name} SET ${column:name} = ${column:name} + ${amount:csv} WHERE id = ${id:csv} RETURNING *', {
                table: toTable,
                column: column,
                amount: amount,
                id: toId
            })
        ]);
    }).then(result => {
         return result;
    }).catch(err => {
        throw err;
    });
 };

Here is the middleware that uses it

const transferEnvelopeBudgetByIds = async (req, res, next) => {
    try{
        req.updatedEnvelopes = await transferColumnAmount("envelopes", "envelopes", req.envelopeFromId, req.envelopeToId, "budget", req.transferBudget);
        next();
    }catch(err){
        next(err);
    }
};

Here is the error handling middleware

apiRouter.use((err, req, res, next) => {
    if(!err.status){
      err.status = 500;
    }
    res.status(err.status).send(err.message);
  });
0

There are 0 answers