UNPKG

@gp_jcisneros/errors

Version:

Error handling utilities for GreenPay microservices and validation middleware

118 lines (108 loc) 3.16 kB
const { CustomError } = require('./CustomError'); /** * Validation error class for input validation failures */ class ValidationError extends CustomError { constructor(message, field = null, value = null) { super(message, { errorCode: `VALIDATION_${field ? field.toUpperCase() : 'GENERAL'}`, description: message, integration: 'validation-service', statusCode: 400 }); this.name = 'ValidationError'; this.type = 'VALIDATION_ERROR'; this.field = field; this.value = value; } /** * Create a validation error for a specific field * @param {string} field - Field name that failed validation * @param {string} message - Error message * @param {any} value - Invalid value * @returns {ValidationError} - Validation error */ static forField(field, message, value = null) { return new ValidationError(message, field, value); } /** * Create a required field error * @param {string} field - Field name * @returns {ValidationError} - Required field error */ static required(field) { return new ValidationError(`${field} is required`, field, null); } /** * Create an invalid format error * @param {string} field - Field name * @param {string} format - Expected format * @param {any} value - Invalid value * @returns {ValidationError} - Invalid format error */ static invalidFormat(field, format, value = null) { return new ValidationError( `${field} must be in format: ${format}`, field, value ); } /** * Create a minimum length error * @param {string} field - Field name * @param {number} minLength - Minimum length * @param {any} value - Invalid value * @returns {ValidationError} - Minimum length error */ static minLength(field, minLength, value = null) { return new ValidationError( `${field} must be at least ${minLength} characters long`, field, value ); } /** * Create a maximum length error * @param {string} field - Field name * @param {number} maxLength - Maximum length * @param {any} value - Invalid value * @returns {ValidationError} - Maximum length error */ static maxLength(field, maxLength, value = null) { return new ValidationError( `${field} must be no more than ${maxLength} characters long`, field, value ); } /** * Create an invalid email error * @param {string} field - Field name * @param {any} value - Invalid value * @returns {ValidationError} - Invalid email error */ static invalidEmail(field = 'email', value = null) { return new ValidationError( `${field} must be a valid email address`, field, value ); } /** * Get validation error details * @returns {Object} - Validation error details */ getValidationDetails() { return { field: this.field, value: this.value, message: this.message, type: this.type, // Required fields errorCode: this.errorCode, description: this.description, integration: this.integration, }; } } module.exports = { ValidationError };