QuocAnhJ / node_mongo_boilerplate

2 stars 4 forks source link

httpResponseHelper to be HttpResponseHandler #4

Closed pmnhatdn closed 6 years ago

pmnhatdn commented 6 years ago

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?

QuocAnhJ commented 6 years ago

+1. Fixed!