Error Handling
The ToughClicks JavaScript library provides a robust error handling system that allows your application to gracefully handle internal errors and network issues. Proper error handling ensures a good user experience even when things go wrong.
Overview
When ToughClicks experiences an internal error, the library:
- Fires the
tc-internal-errorevent immediately - Includes error details in the event payload
- Prevents further processing to avoid inconsistent state
- Allows your application to decide how to proceed
Your application can then:
- Display user-friendly error messages
- Log errors for monitoring and debugging
- Implement retry logic
- Decide between fail-open or fail-closed behavior
Listening for Errors
Use the tc-internal-error event to handle errors. This event fires whenever the library experiences an internal error.
Basic example:
const { ToughClicks } = window.ToughClicks;
const tc = new ToughClicks(clientToken, packetId);
tc.on('tc-internal-error', (e) => {
console.error('ToughClicks error:', e.detail.error);
// Display user-friendly message
alert('We encountered an issue processing your agreement. Please try again later.');
});
See Events for detailed information about event listeners.
Error Event Details
The tc-internal-error event includes error information in event.detail:
{
error: Error // JavaScript Error object
}
Example accessing error details:
tc.on('tc-internal-error', (e) => {
const error = e.detail.error;
console.error('Error message:', error.message);
console.error('Error stack:', error.stack);
// Log to error tracking service
errorTracker.captureException(error, {
context: 'ToughClicks',
packetId: packetId,
userId: currentUser.id
});
});
Common Error Scenarios
Network Errors
Network issues are the most common cause of errors:
- Internet connectivity problems
- API server downtime
- Timeout errors
- DNS resolution failures
Example handling:
tc.on('tc-internal-error', (e) => {
const error = e.detail.error;
// Check if it's a network error
if (error.message.includes('network') || error.message.includes('fetch')) {
showErrorMessage(
'Unable to connect. Please check your internet connection and try again.'
);
} else {
showErrorMessage(
'An unexpected error occurred. Please try again later.'
);
}
});
API Errors
API errors occur when the ToughClicks service returns an error response:
- Invalid authentication tokens
- Packet not found
- Rate limiting
- Server errors
Example handling:
tc.on('tc-internal-error', (e) => {
const error = e.detail.error;
// Log for debugging
console.error('API error:', {
message: error.message,
timestamp: new Date().toISOString(),
packetId: packetId
});
// Show generic message to user
showErrorMessage(
'We are unable to process your request at this time. Please contact support if this problem persists.'
);
});
Configuration Errors
Configuration errors happen when the library is misconfigured:
- Invalid display options
- Missing required fields
- Invalid container ID
Note: These often throw synchronously rather than firing the error event.
Error Handling Strategies
Fail-Open vs Fail-Closed
When an error occurs, you must decide whether to allow the user to proceed or block them. This decision depends on your use case.
Fail-Open (Allow User to Proceed)
Users can continue even if ToughClicks fails. You'll catch them on their next visit.
When to use:
- You have a force reacceptance flow on subsequent logins
- User access is more important than immediate compliance
- You can verify compliance later
- You have alternative verification methods
Example:
tc.on('tc-internal-error', (e) => {
console.error('ToughClicks error:', e.detail.error);
// Log error for monitoring
logError('toughclicks-error', e.detail.error);
// Show warning but allow user to proceed
showWarning(
'We could not record your agreement at this time. You may be asked to accept terms again on your next visit.'
);
// Enable the submit button
document.getElementById('submit-btn').disabled = false;
// Set flag to check on next login
localStorage.setItem('tc-compliance-check-needed', 'true');
});
Fail-Closed (Block User)
Users cannot proceed if ToughClicks fails. They must try again later.
When to use:
- Legal compliance is critical
- You must have acceptance records before granting access
- No alternative verification method exists
- Regulatory requirements mandate it
Example:
tc.on('tc-internal-error', (e) => {
console.error('ToughClicks error:', e.detail.error);
// Log error for monitoring
logError('toughclicks-error', e.detail.error);
// Show error and block user
showError(
'We are unable to process your agreement at this time. Please try again later or contact support for assistance.'
);
// Keep submit button disabled
document.getElementById('submit-btn').disabled = true;
// Show retry button
document.getElementById('retry-btn').style.display = 'block';
});
Retry Logic
Implement retry logic for transient errors:
let retryCount = 0;
const MAX_RETRIES = 3;
tc.on('tc-internal-error', (e) => {
console.error('ToughClicks error:', e.detail.error);
if (retryCount < MAX_RETRIES) {
retryCount++;
showMessage(
`Connection error. Retrying (${retryCount}/${MAX_RETRIES})...`
);
// Retry after a delay
setTimeout(() => {
tc.accept().catch(err => {
console.error('Retry failed:', err);
});
}, 2000 * retryCount); // Exponential backoff
} else {
showError(
'Unable to process your agreement after multiple attempts. Please try again later.'
);
}
});
// Reset retry count on success
tc.on('tc-accepted', (e) => {
retryCount = 0;
});
User Notification
Always inform users when errors occur:
tc.on('tc-internal-error', (e) => {
console.error('ToughClicks error:', e.detail.error);
// Show user-friendly notification
const notification = document.createElement('div');
notification.className = 'error-notification';
notification.innerHTML = `
<strong>Connection Error</strong>
<p>We're having trouble processing your agreement. Please check your connection and try again.</p>
<button onclick="location.reload()">Retry</button>
`;
document.body.appendChild(notification);
});
Logging and Monitoring
Send errors to your logging/monitoring service:
Sentry
tc.on('tc-internal-error', (e) => {
Sentry.captureException(e.detail.error, {
tags: {
component: 'toughclicks',
packetId: packetId
},
extra: {
clientToken: clientToken,
userId: currentUser?.id,
timestamp: new Date().toISOString()
}
});
// Show user error message
showErrorNotification();
});
Google Analytics / GA4
tc.on('tc-internal-error', (e) => {
gtag('event', 'exception', {
description: e.detail.error.message,
fatal: false,
category: 'ToughClicks',
label: 'Internal Error'
});
});
Custom Logging Service
tc.on('tc-internal-error', (e) => {
fetch('/api/log-error', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
service: 'toughclicks',
error: {
message: e.detail.error.message,
stack: e.detail.error.stack
},
context: {
packetId: packetId,
userId: currentUser?.id,
url: window.location.href,
timestamp: new Date().toISOString()
}
})
}).catch(err => {
console.error('Failed to log error:', err);
});
});
Complete Error Handling Example
Here's a comprehensive error handling implementation:
const { ToughClicks } = window.ToughClicks;
const tc = new ToughClicks(clientToken, packetId);
// Error handling configuration
const ERROR_CONFIG = {
maxRetries: 3,
retryDelay: 2000,
failOpen: false // Set to true for fail-open behavior
};
let retryCount = 0;
// Configure ToughClicks
tc.setDisplayOptions({
containerId: 'tc-container',
displayMethod: 'Individual',
signerIdSelector: 'email',
manualAcceptance: true
});
// Handle internal errors
tc.on('tc-internal-error', (e) => {
const error = e.detail.error;
// Log to console
console.error('ToughClicks error:', error);
// Log to monitoring service
logToMonitoring({
service: 'toughclicks',
error: error,
packetId: packetId,
userId: currentUser?.id
});
// Attempt retry if under limit
if (retryCount < ERROR_CONFIG.maxRetries) {
retryCount++;
showNotification(
`Connection error. Retrying (${retryCount}/${ERROR_CONFIG.maxRetries})...`,
'warning'
);
setTimeout(() => {
tc.accept().catch(retryError => {
console.error('Retry failed:', retryError);
});
}, ERROR_CONFIG.retryDelay * retryCount);
return;
}
// Max retries exceeded - decide fail-open or fail-closed
if (ERROR_CONFIG.failOpen) {
// Fail-open: Allow user to proceed with warning
showNotification(
'We could not record your agreement. You may need to accept terms again on your next visit.',
'warning'
);
localStorage.setItem('tc-compliance-pending', 'true');
// Allow form submission
document.getElementById('submit-btn').disabled = false;
} else {
// Fail-closed: Block user
showNotification(
'Unable to process your agreement. Please try again later or contact support.',
'error'
);
// Keep submit button disabled
document.getElementById('submit-btn').disabled = true;
// Show support contact
document.getElementById('support-message').style.display = 'block';
}
});
// Handle successful acceptance
tc.on('tc-accepted', (e) => {
retryCount = 0; // Reset retry count
if (e.detail.allAccepted) {
localStorage.removeItem('tc-compliance-pending');
showNotification('Terms accepted successfully!', 'success');
proceedWithFlow();
}
});
// Manual acceptance
document.getElementById('submit-btn').addEventListener('click', async () => {
const button = document.getElementById('submit-btn');
button.disabled = true;
button.textContent = 'Processing...';
try {
retryCount = 0; // Reset before new attempt
await tc.accept();
} catch (error) {
console.error('Manual acceptance error:', error);
button.disabled = false;
button.textContent = 'Try Again';
}
});
// Helper functions
function showNotification(message, type) {
// Your notification implementation
console.log(`[${type.toUpperCase()}] ${message}`);
}
function logToMonitoring(data) {
// Your monitoring service integration
console.log('Logging to monitoring:', data);
}
function proceedWithFlow() {
// Continue with your application flow
window.location.href = '/dashboard';
}
Best Practices
- Always listen for errors - Don't assume ToughClicks will always succeed
- Log errors - Send errors to a monitoring service for debugging
- Inform users - Show user-friendly error messages, not technical details
- Decide fail-open vs fail-closed - Choose based on your compliance requirements
- Implement retry logic - Handle transient network errors gracefully
- Test error scenarios - Disconnect network and test error handling
- Monitor error rates - Track errors to identify systemic issues
- Document behavior - Document your fail-open/fail-closed decision for your team
Debugging
Enable Verbose Logging
// Log all ToughClicks events for debugging
tc.on('tc-valid', (e) => console.log('tc-valid:', e.detail));
tc.on('tc-accepted', (e) => console.log('tc-accepted:', e.detail));
tc.on('tc-internal-error', (e) => console.error('tc-internal-error:', e.detail));
Simulate Errors
Test error handling by simulating errors:
// Temporarily use invalid credentials to trigger errors
const tc = new ToughClicks('invalid-token', 'invalid-packet');
// Or disable network in DevTools to simulate network errors
Related Documentation
- Events - Complete event system documentation
- Manual Acceptance - Control acceptance timing
- Caching - Cache-related errors and configuration