Instead of just providing methods to be used by controllers ( as its name - helper), this should be a Handler, which generically handles errors or other response type.
So instead of exporting:
buildValidationErrorResponse,
buildDuplicationErrorResponse,
buildPostSuccessResponse,
buildInternalServerErrorResponse,
buildNotFoundErrorResponse,
Publicly export only handleErrors method, which consume the error message and error code to determine the error type, i.e: 500 == 'Internal Server Error' ...
Sample code:
// HttpResponseHandler
handleErrors = (function(err, req, res, next) {
res.status(err.status || 500);
//some condition checks based on the status if needed.
res.render('error', {
message: err.message,
});
}
Export { handleErrors }
//Global routing => register the above as a error handler middleware
app.use(handleErrors);
//Controllers:
Instead of :
if (errors) {
return buildValidationErrorResponse(res, errors);
}
Instead of just providing methods to be used by controllers ( as its name - helper), this should be a Handler, which generically handles errors or other response type.
So instead of exporting: buildValidationErrorResponse, buildDuplicationErrorResponse, buildPostSuccessResponse, buildInternalServerErrorResponse, buildNotFoundErrorResponse,
Publicly export only handleErrors method, which consume the error message and error code to determine the error type, i.e: 500 == 'Internal Server Error' ...
Sample code: // HttpResponseHandler handleErrors = (function(err, req, res, next) { res.status(err.status || 500); //some condition checks based on the status if needed. res.render('error', { message: err.message, }); } Export { handleErrors }
//Global routing => register the above as a error handler middleware app.use(handleErrors);
//Controllers: Instead of : if (errors) { return buildValidationErrorResponse(res, errors); }
=>> If (errors) { next(errors); return; }
Instead of
catch (err) { buildInternalServerErrorResponse(res); }
Simply : catch(err) { next(err) }
Pretty generic huh?