I'm working on an Express app, and one of the routes looks like this
router.put(
'/countries/:countryId/regions/:regionId/cities/:cityId',
runAsyncWrapper(updateCity),
);
Inside the controller I have these checks
const {
params: { countryId, regionId, cityId },
body,
} = req;
if (!countryId) throw new CountryIdRequired();
if (!regionId) throw new RegionIdRequired();
if (!cityId) throw new CityIdRequired();
Do those checks even make any sense? Since these IDs are used in the route string, is there any chance that this controller (which is used only with that one route) will be called, and some of the params will be null or undefined?
CodePudding user response:
Express should answer with HTTP 404 if your params are not set.
CodePudding user response:
You could try something like this:
exports.getLocation = (req, result) => { // getLocation is the controller
const {city_id, country_id, region_id} = req.params
if (city_id === undefined || country_id === undefined || region_id === undefined) {
result.status(400).send({
message: 'Make sure all fields are filled',
statusCode: 400
})
} else {
// rest of the code
}
If the params are required and the user has sent a an API request without this data in it, you will receive it as undefined in this case, so this is a possible error handling for you, hope it helps.
