I'm using mongoose to interact with db and use the errorHandler middleware to handle the exception error
The controller :
const asyncHandler = require('express-async-handler');
const Contact = require('../models/contactModel');
const getContact = asyncHandler(async (req, res) => {
const contact = await Contact.findById(req.params.id);
if (!contact) {
res.status(404);
throw new Error('Contact not found');
}
res.status(200).json(contact);
});
errorHandler middleware :
const { constants } = require('../constants');
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode ? res.statusCode : 500;
switch (statusCode) {
case constants.VALIDATION_ERROR:
res.json({
title: 'Validation failed',
message: err.message,
stackTrace: err.stack
});
case constants.UNAUTHORIZED:
res.json({
title: 'Unauthorized',
message: err.message,
stackTrace: err.stack
});
case constants.FORBIDDEN:
res.json({
title: 'Forbidden',
message: err.message,
stackTrace: err.stack
});
case constants.NOT_FOUND:
res.json({
title: 'Not found',
message: err.message,
stackTrace: err.stack
});
case constants.SERVER_ERROR:
res.json({
title: 'Server error',
message: err.message,
stackTrace: err.stack
});
default:
console.log('No error, all is well !');
break;
}
};
Its working fine If the document is found,
But if it doesn't get the result the error handler middleware seems to always get the default switch case instead of returning the 404 error,
how can i solve this ?