Reputation: 1857
employeeData.js
function getById(id) {
return dbPromise.one(); // using pg-promise
}
employeeService.js
function getInfoById(id) {
return employeeData.getXYZ(id); // purposefully calling a function that does not exist in the employeeData module
}
employeeApi.js // Express route function
const getInfoById = (req, res) {
employeeService.getInfoById(123)
.then(response => {
res.json(response);
})
.catch(err => {
res.json(err); // this is not being triggered
});
}
In the employeeService
above I purposefully mis-typed the function name and I think it should throw an undefined error for calling a function getXYZ
that does not exist in the employeeData.js
. However, the catch block in employeeApi.js
is not called.
Can you suggest what I might be missing here?
Upvotes: 0
Views: 2891
Reputation: 665448
I think it should throw an undefined error for calling a function that does not exist
Yes, it does that. It throws an exception, it does not return a promise. As such, there is no promise object on which the then(…).catch(…)
methods could be invoked.
However, the catch block is not called.
There is no catch
block, it's just a method call - which doesn't happen because there's an exception. To catch it, you would need an actual try
/catch
block.
But that would look weird, and that's the reason why promise-returning functions should never throw. You could wrap the code with the mistake in a new Promise
executor which would catch them, but the simpler choice is to use async
/await
syntax which guarantees to always return a promise (and reject it in case of an exception in the function body).
async function getInfoById {
return employeeData.getXYZ(123);
}
Upvotes: 4