2019-04-21 23:55:22 +02:00
|
|
|
/**
|
2021-08-13 10:26:33 +04:00
|
|
|
* @description Centralized error handling for API requests.
|
2019-04-21 23:55:22 +02:00
|
|
|
* @param {Function} next
|
2020-10-20 12:02:56 +13:00
|
|
|
* @returns {Function} handleErrorClosure
|
2019-04-21 23:55:22 +02:00
|
|
|
*/
|
2015-10-21 12:51:01 +01:00
|
|
|
function handleError(next) {
|
2020-10-20 12:02:56 +13:00
|
|
|
return function handleErrorClosure(err) {
|
2019-04-21 23:55:22 +02:00
|
|
|
// CASE: if we've thrown an error message of type: 'NotFound' then we found no path match, try next router!
|
2015-10-21 12:51:01 +01:00
|
|
|
if (err.errorType === 'NotFoundError') {
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
2019-03-11 19:40:51 +01:00
|
|
|
// CASE: the site should not output validation errors e.g. you ask for /feed.xml/ and it tries to fetch
|
|
|
|
// this post from Content API (by slug), but this is not a valid slug. With dynamic routing we cannot
|
|
|
|
// add a regex to the target express route, because we don't know if people use /:slug/ or not. It's dynamic.
|
|
|
|
if (err.errorType === 'ValidationError') {
|
|
|
|
// @NOTE: Just try next router, it will end in a 404 if no router can resolve the request.
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
|
2015-10-21 12:51:01 +01:00
|
|
|
return next(err);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = handleError;
|