Troubleshooting Guide
Common issues and solutions for SecureHealth, including error messages, debugging tips, and performance optimization.
Common Issuesβ
Database Connection Issuesβ
Problem: MongoDB Connection Failedβ
Error Message:
MongoDB connection failed: Authentication failed
Solutions:
- Check MongoDB connection string format
- Verify username and password
- Ensure IP whitelist includes your server
- Check network connectivity
Debug Steps:
# Test MongoDB connection
mongosh "mongodb+srv://username:password@cluster.mongodb.net/securehealth"
# Check network connectivity
ping cluster.mongodb.net
# Verify IP whitelist
# Check MongoDB Atlas Network Access settings
Problem: Encryption Key Issuesβ
Error Message:
Encryption key not found or invalid
Solutions:
- Verify encryption key ID exists
- Check master key format
- Ensure key vault is accessible
- Verify key permissions
Debug Steps:
# Check encryption key
node -e "
const { MongoClient } = require('mongodb');
const client = new MongoClient(process.env.DATABASE_URL);
client.connect().then(() => {
const keyVault = client.db('encryption').collection('__keyVault');
return keyVault.findOne({_id: process.env.MONGODB_ENCRYPTION_KEY_ID});
}).then(key => {
console.log('Key found:', !!key);
client.close();
});
"
Authentication Issuesβ
Problem: JWT Token Invalidβ
Error Message:
JWT token is invalid or expired
Solutions:
- Check JWT secret configuration
- Verify token expiration time
- Ensure token format is correct
- Check clock synchronization
Debug Steps:
# Decode JWT token
echo "your-jwt-token" | base64 -d
# Check token expiration
node -e "
const jwt = require('jsonwebtoken');
const token = 'your-jwt-token';
try {
const decoded = jwt.decode(token);
console.log('Token expires:', new Date(decoded.exp * 1000));
} catch (e) {
console.log('Invalid token:', e.message);
}
"
Problem: Role-Based Access Deniedβ
Error Message:
Access denied: Insufficient permissions
Solutions:
- Verify user roles
- Check role assignments
- Ensure proper role hierarchy
- Verify resource permissions
Debug Steps:
// Check user roles
$user = $this->getUser();
$roles = $user->getRoles();
$permissions = $this->getUserPermissions($user);
// Log role information
$this->logger->info('User roles', ['roles' => $roles, 'permissions' => $permissions]);
Encryption Issuesβ
Problem: Encryption/Decryption Failedβ
Error Message:
Failed to encrypt/decrypt data
Solutions:
- Check encryption configuration
- Verify key vault access
- Ensure proper schema mapping
- Check data format compatibility
Debug Steps:
// Test encryption
$encrypted = $this->encryptionService->encrypt('test data');
$decrypted = $this->encryptionService->decrypt($encrypted);
if ($decrypted !== 'test data') {
throw new \Exception('Encryption test failed');
}
Problem: Query Performance Issuesβ
Error Message:
Query execution timeout
Solutions:
- Add database indexes
- Optimize query patterns
- Use proper encryption types
- Monitor query performance
Debug Steps:
# Check query performance
mongosh --eval "
db.patients.explain('executionStats').find({firstName: 'John'})
"
# Check indexes
mongosh --eval "
db.patients.getIndexes()
"
API Issuesβ
Problem: CORS Errorsβ
Error Message:
CORS policy: No 'Access-Control-Allow-Origin' header
Solutions:
- Check CORS configuration
- Verify allowed origins
- Ensure proper headers
- Check preflight requests
Debug Steps:
# Test CORS
curl -H "Origin: https://securehealth.dev" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: Content-Type" \
-X OPTIONS \
https://api.securehealth.dev/api/patients
Problem: Rate Limitingβ
Error Message:
Rate limit exceeded
Solutions:
- Check rate limit configuration
- Implement proper caching
- Use request queuing
- Monitor API usage
Debug Steps:
# Check rate limit headers
curl -I https://api.securehealth.dev/api/patients
# Response headers:
# X-RateLimit-Limit: 100
# X-RateLimit-Remaining: 95
# X-RateLimit-Reset: 1642248000
Performance Issuesβ
Slow Database Queriesβ
Symptoms:
- High response times
- Database connection timeouts
- Memory usage spikes
Solutions:
- Add Indexes
// Create indexes for encrypted fields
db.patients.createIndex({ "firstName": 1 })
db.patients.createIndex({ "lastName": 1 })
db.patients.createIndex({ "dateOfBirth": 1 })
- Optimize Queries
// Use projection to limit returned fields
$patients = $this->patientRepository->findBy(
['firstName' => 'John'],
['firstName' => 'ASC'],
10,
0,
['firstName', 'lastName', 'dateOfBirth']
);
- Use Connection Pooling
# config/packages/doctrine_mongodb.yaml
doctrine_mongodb:
connections:
default:
options:
maxPoolSize: 10
minPoolSize: 1
maxIdleTimeMS: 30000
Memory Issuesβ
Symptoms:
- High memory usage
- Out of memory errors
- Slow garbage collection
Solutions:
- Optimize Data Loading
// Use pagination
$patients = $this->patientRepository->findBy(
[],
[],
$limit,
$offset
);
// Use lazy loading
$patient = $this->patientRepository->find($id);
$labResults = $patient->getLabResults(); // Lazy loaded
- Implement Caching
// Use Redis cache
$cacheKey = "patient_{$id}";
$patient = $this->cache->get($cacheKey, function() use ($id) {
return $this->patientRepository->find($id);
});
Debugging Tipsβ
Enable Debug Modeβ
# Set debug environment
APP_ENV=dev
APP_DEBUG=true
LOG_LEVEL=debug
Log Analysisβ
# Monitor logs in real-time
tail -f /var/log/securehealth/app.log
# Search for specific errors
grep "ERROR" /var/log/securehealth/app.log
# Analyze performance
grep "slow query" /var/log/securehealth/app.log
Database Monitoringβ
# Check database status
mongosh --eval "db.runCommand({serverStatus: 1})"
# Monitor connections
mongosh --eval "db.runCommand({currentOp: 1})"
# Check index usage
mongosh --eval "db.patients.aggregate([{$indexStats: {}}])"
API Testingβ
# Test API endpoints
curl -X GET https://api.securehealth.dev/api/patients \
-H "Authorization: Bearer your-jwt-token"
# Test with verbose output
curl -v -X POST https://api.securehealth.dev/api/patients \
-H "Content-Type: application/json" \
-H "Authorization: Bearer your-jwt-token" \
-d '{"firstName": "John", "lastName": "Doe"}'
Error Codes Referenceβ
HTTP Status Codesβ
- 400 Bad Request: Invalid request data
- 401 Unauthorized: Authentication required
- 403 Forbidden: Insufficient permissions
- 404 Not Found: Resource not found
- 422 Unprocessable Entity: Validation errors
- 429 Too Many Requests: Rate limit exceeded
- 500 Internal Server Error: Server error
- 503 Service Unavailable: Service temporarily unavailable
Application Error Codesβ
- ENCRYPTION_ERROR: Encryption/decryption failed
- DATABASE_ERROR: Database operation failed
- VALIDATION_ERROR: Input validation failed
- AUTHENTICATION_ERROR: Authentication failed
- AUTHORIZATION_ERROR: Authorization failed
- RATE_LIMIT_ERROR: Rate limit exceeded
- AUDIT_ERROR: Audit logging failed
Getting Helpβ
Support Channelsβ
- GitHub Issues: Report bugs and feature requests
- Documentation: Check this guide and API reference
- Community Forum: Ask questions and share solutions
- Email Support: Contact support@securehealth.dev
Reporting Issuesβ
When reporting issues, include:
-
Environment Details
- Operating system
- PHP version
- MongoDB version
- Application version
-
Error Information
- Error message
- Stack trace
- Log files
- Steps to reproduce
-
Configuration
- Environment variables (sanitized)
- Configuration files
- Database schema
Next Stepsβ
- API Endpoints Reference - Complete API documentation
- Configuration Reference - All configuration options
- Environment Variables - Environment setup
- Glossary - Technical terms and definitions