Reputation: 339
Suppose I have an api.js:
const {somefunction} = require('../controllers/some-controller');
app.get('/data/', somefunction);
some-controller.js:
exports.somefunction = async (req, res,next) => {
const someVariable = req.params.variable
try {
console.log('status',res.statusCode) **//status code is: 200**
const Details = await collectionName.find({}).exec()
res.send(Details)
} catch {
console.log('status',res.statusCode) **//Here also,status code is: 200**
next(ApiError.dbError('Internal Server Error')); //middleware for error handling gives output
//as ApiError { code: 500, message:
//'Internal Server Error' }
return;
}
};
Say I wrote some wrong variable name in res.send(Detaaal) and it goes to catch block Here even in catch block status code is 200.
I'm trying to understand at what condition is status code different. Why is status code response on fail inside catch block didn't give me 500 status code.
Upvotes: 0
Views: 59
Reputation: 943510
200 is the default code and nothing has happened that would change that.
You haven't written code to change it and, while an exception has been thrown, you caught it, so it never hits Express' own catch
logic which would set a 500 error.
The next
function, on the other hand, does appear to change it, but you are looking at the value before running that function.
Upvotes: 1
Reputation: 454
sorry about my poor english
your logic in here cause the problem you are getting everything in collection even its empty
const Details = await collectionName.find({}).exec()
when collection is empty there was no error just return empty array like this[] You must create a condition to prevent an empty submission from being sent here is my solution
exports.somefunction = async (req, res,next) => {
const someVariable = req.params.variable
try {
console.log('status',res.statusCode) **//status code is: 200**
const Details = await collectionName.find({}).exec()
if (Details.length===0) {
return res.status(404).send();
}
res.send(Details)
} catch {
console.log('status',res.statusCode) **//Here also,status code is: 200**
next(ApiError.dbError('Internal Server Error')); //middleware for error handling gives output
//as ApiError { code: 500, message:
//'Internal Server Error' }
return;
}
};
Upvotes: 1