Which principle does this error handling implementation violate, and how can it be improved using DRY?
function handleUserError(error) {
console.error('User Error:', error);
logToService('User Error:', error);
showNotification('Error occurred while processing user data');
}
function handlePaymentError(error) {
console.error('Payment Error:', error);
logToService('Payment Error:', error);
showNotification('Error occurred while processing payment');
}
function handleProductError(error) {
console.error('Product Error:', error);
logToService('Product Error:', error);
showNotification('Error occurred while processing product');
This code violates the DRY principle by duplicating the error handling logic across multiple functions. Each function follows the same pattern of logging, service logging, and notification. A better approach would be to create a generic error handler:
function handleError(context, error) {
console.error(`${context} Error:`, error);
logToService(`${context} Error:`, error);
showNotification(`Error occurred while processing ${context.toLowerCase()}`);
}
// Usage:
handleError('User', error);
handleError('Payment', error);
handleError('Product', error);
This implementation reduces code duplication and makes it easier to modify the error handling logic across the application.