diff --git a/helpers/controller.helper.js b/helpers/controller.helper.js index 3fbeb9b..2cacd4d 100644 --- a/helpers/controller.helper.js +++ b/helpers/controller.helper.js @@ -2,12 +2,27 @@ const _ = require('lodash'); const httpStatus = require('http-status'); +const Sequelize = require('sequelize'); + //////////////////////////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS //////////////////////////////////////////////////////////////////////////////// function buildErrorLog(err) { + if (err instanceof Sequelize.ValidationError) { + return { + message: err.message, + httpCode: httpStatus.UNPROCESSABLE_ENTITY, // <- datos no vĂ¡lidos + code: (err.parent) ? err.parent.code : '', + payload: err.fields, + } + } + return buildErrorLogOriginal(err); +} + + +function buildErrorLogOriginal(err) { let errorLog; if (_.isUndefined(err)) { errorLog = 'Error not defined'; @@ -26,9 +41,11 @@ function buildErrorResponse(nameController, nameMethod, error) { const errorDescription = buildErrorLog(error); const jsonResultFailed = { - code: httpStatus.INTERNAL_SERVER_ERROR, - message: 'Internal Server Error', - description: `Internal Application Error in ${nameController}:${nameMethod}. ${errorDescription}` + statusCode: errorDescription.httpCode ? errorDescription.httpCode : httpStatus.INTERNAL_SERVER_ERROR, + message: errorDescription.message ? errorDescription.message : 'Internal Server Error', + code: errorDescription.code ? errorDescription.code : 'Undefined', + description: `Internal Application Error in ${nameController}:${nameMethod}.`, + payload: errorDescription } return jsonResultFailed; } @@ -108,7 +125,7 @@ function extractParamsFromRequest(req, res, extraParams = {}) { function handleErrorResponse(controllerName, methodName, error, res) { const jsonResultFailed = buildErrorResponse(controllerName, methodName, error); - res.status(httpStatus.INTERNAL_SERVER_ERROR).send(jsonResultFailed); + res.status(jsonResultFailed.statusCode).send(jsonResultFailed); } function handleResultResponse(result, totalCount = null, params, res, statusCode = httpStatus.OK) {