0
votes

I have the following function which reads an array and the passes it to my server

let storedProcedure = async (params, storedProcedureName) => {
const pool = await getOrCreatePool()
let request = await pool.request()
params.forEach((parameter) => {
    parameterDirection = parameter.isOutput ? 'output' : 'input';
    request = request[parameterDirection](parameter.name, parameter.type, parameter.value)
});
try {
    return await request.execute(storedProcedureName)
} catch(err) {
    console.error('StoredProcedure error', err);
    return null;
}
}

and i call it like this

apiRoutes.put('/update/:leadid', function(req, res) {

var param = validateUpdateLead(req.body, req.params.leadid)   
var promise = sqlUtil.storedProcedure(param,'sp_Leads_UPD')


       promise.then((result) => 
        {
            console.log('LeadID:' + req.params.leadid + ' Updated - ' + result.rowsAffected[0] + ' Rows Effected')
            res.json({ success: true, RowsAffected : result.rowsAffected[0], UpdatedLeadID :req.params.leadid }).status(200)  
        })
        .catch(err)

        {
        res.send('error':err )
        }
 })

when i do that my system nodeJs complains that "ReferenceError: err is not defined" so the question is how can i pass the error from my function to the call and catch it ? When i have calls which fail because of one or the or the reason i get (node:1512) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'leadid' of undefined at promise.then (C:\nodeRoot\CRM-NodeJS\routes\leads.js:55:52) at process._tickCallback (internal/process/next_tick.js:68:7) (node:1512) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) So i hope this is something simple to fix

1

1 Answers

0
votes

(node:1512) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'leadid' of undefined at promise.then (C:\nodeRoot\CRM-NodeJS\routes\leads.js:55:52) at process._tickCallback (internal/process/next_tick.js:68:7) (node:1512)

So this is happening because you are returning null when there is an error in stored procedure, to properly behave you have to throw an error from the stored procedure like

console.error('StoredProcedure error', err);
throw new Error(err);

or simply you can just remove try catch from the stored procedure and let the route function handle the error like

let storedProcedure = async (params, storedProcedureName) => {
   const pool = await getOrCreatePool()
   let request = await pool.request()
   params.forEach((parameter) => {
      parameterDirection = parameter.isOutput ? 'output' : 'input';
      request = request[parameterDirection(parameter.name, parameter.type, parameter.value)
   });

  return await request.execute(storedProcedureName)
}