Skip to content

Debugging and Error Recovery Patterns

Debugging is no longer about manually adding print statements and staring at stack traces. With Cursor’s AI assistance, you can diagnose issues in minutes that would traditionally take hours, automatically fix errors, and even prevent bugs before they happen.

The most powerful debugging pattern: Let AI add logging, run code, analyze output, and fix issues automatically.

  1. AI adds strategic logging

    Agent: Add logging to understand why user sessions are expiring
  2. Run code with instrumentation

    Agent executes code, captures all log output
  3. AI analyzes logs

    Based on logs: "Sessions expire because cookie lacks
    Secure flag on HTTPS connections"
  4. Automatic fix generation

    Agent fixes the issue and verifies the solution
User: The payment processing is failing intermittently
Agent: I'll add strategic logging to diagnose this issue.
[Adds logging around payment API calls, database transactions,
and error handling]
Running the payment flow 10 times to capture the pattern...
Analysis: The issue occurs when:
1. Database connection pool is exhausted (8/10 failures)
2. Payment API rate limit hit (2/10 failures)
Let me fix both issues:
- Adding connection pool retry logic
- Implementing exponential backoff for API calls
[Implements fixes]
[Runs 50 more tests - 100% success rate]
The intermittent failures are now resolved.

Use @Linter-errors to automatically fix code quality issues:

TypeScript Errors

Agent: Run tsc and fix all TypeScript errors

With YOLO mode, Agent iterates until build passes

ESLint Issues

Agent: Fix all ESLint warnings and errors

AI understands intent behind lint rules

Python Type Hints

Agent: Add missing type hints based on mypy output

Comprehensive type safety without manual work

Format & Style

Agent: Run prettier and fix all formatting

Consistent code style automatically maintained

Terminal window
# Create a pre-PR command that runs all checks
{
"scripts": {
"pre-pr": "npm run lint && npm run test && npm run build"
}
}

Then simply:

Agent: Run npm run pre-pr and fix any issues until it passes

Connect Cursor to production error tracking for automated resolution:

User: Check Sentry for recent errors and create fixes
Agent: Analyzing Sentry dashboard...
Found 3 critical issues:
1. NullPointerException in UserService.getProfile() - 147 occurrences
2. API timeout in PaymentGateway - 23 occurrences
3. Invalid date format in ReportGenerator - 89 occurrences
Starting with the most frequent issue:
[Opens UserService.java]
The null pointer occurs when user.getPreferences() returns null
but we don't check before calling .getTheme().
Creating fix with null safety:
  1. Error Detection - Monitor error tracking systems
  2. Root Cause Analysis - AI analyzes stack traces and patterns
  3. Reproduction - Agent attempts to reproduce locally
  4. Fix Generation - Creates targeted fix for root cause
  5. Verification - Tests fix prevents recurrence
  6. PR Creation - Submits fix for review

Use Cursor’s bug finder before committing:

Command: Ctrl+Shift+P → "bug finder"
Agent analyzes your changes and identifies:
- Potential null pointer exceptions
- Missing error handling
- Security vulnerabilities
- Performance issues
- Logic errors
Bug Finder Results:
1. 🔴 Critical: Potential SQL injection in UserQuery.java:45
- User input directly concatenated into query
- Suggested fix: Use parameterized queries
2. 🟡 Warning: Missing null check in calculateTotal():
- items parameter could be null
- Suggested fix: Add null guard clause
3. 🟡 Warning: Inefficient loop in processOrders():
- N+1 query pattern detected
- Suggested fix: Use batch loading
Agent: Would you like me to fix these issues?

AI can identify and fix performance bottlenecks:

Agent: Profile the slow endpoint and identify bottlenecks
Running performance profiler...
Results:
- 45% time in database queries
- 30% time in JSON serialization
- 15% time in business logic
- 10% other
Main bottleneck: Missing database index on user_id
Agent: Compare working version (commit abc123) with broken version
to identify what caused the regression
Analyzing differences...
The issue was introduced in commit def456:
- Changed authentication flow
- Removed session validation step
- This causes immediate logout on page refresh
Reverting problematic change and adding test to prevent regression
Agent: Debug why orders are failing in microservices architecture
Tracing request flow:
1. ✓ Order Service receives request
2. ✓ Inventory Service reserves items
3. ✗ Payment Service times out
4. ✗ Order Service rollback fails
Root cause: Payment Service database connection pool exhausted
Secondary issue: Rollback transaction missing timeout handling
Fixing both issues...
Agent: This test passes locally but fails in CI. Investigating...
Adding timing logs around critical sections...
Found race condition:
- Test assumes API call completes before UI update
- In CI (slower environment), UI updates first
- Test checks for data that hasn't loaded yet
Adding proper async/await and wait conditions
Agent: The last deployment caused errors. Rolling back...
1. Identifying last working version from Git tags
2. Creating revert PR for problematic changes
3. Running tests to ensure rollback is clean
4. Deploying previous stable version
5. Creating incident report with root cause
# Configure self-healing behaviors
Agent: Monitor application health and auto-fix common issues:
- If memory usage > 80%: Trigger garbage collection
- If response time > 2s: Clear caches and restart workers
- If error rate > 5%: Switch to degraded mode
- If database connection fails: Attempt reconnection with backoff

Frontend + Backend

Agent traces issues across full stack, from UI to database

Async Operations

AI adds timing logs to identify race conditions and deadlocks

Third-Party APIs

Mock external services to isolate issues and test error cases

Production vs Local

Agent helps reproduce production issues in local environment

Test failing: UserAuthentication.test.js
Agent: Let me debug this test failure.
1. Running test in isolation - FAILS
2. Adding verbose logging to test
3. Test expects 'user.role' but getting undefined
4. Checking recent changes...
5. Found: Schema migration added 'role' but seed data wasn't updated
6. Updating test fixtures with role field
7. Test now passes ✓
URGENT: Users can't log in - production issue
Agent: Investigating login failure...
1. Checking recent deployments (2 hours ago)
2. Examining error logs: "Invalid JWT secret"
3. Environment variable JWT_SECRET not set in production
4. Creating hotfix:
- Adding fallback for missing env var
- Logging warning when using fallback
- Creating urgent PR
Fix deployed. Login restored.
Total resolution time: 8 minutes.

When Cursor itself has problems:

Solution:
1. Run network diagnostics: Settings → Network → Run Diagnostics
2. Check firewall/proxy settings
3. Try HTTP/1.1 fallback if HTTP/2 is blocked
4. Verify internet connectivity

Defensive Coding

Let AI add null checks, input validation, and error boundaries

Early Testing

Write tests with implementation to catch issues immediately

Type Safety

Use TypeScript/type hints to prevent runtime errors

Code Reviews

BugBot catches issues before they reach production

Track these metrics to see improvement:

  • Mean Time to Resolution (MTTR): Should decrease by 40%+
  • Bugs Caught Pre-Production: Increase with AI reviews
  • Debugging Sessions Length: Shorter with AI assistance
  • Production Incidents: Fewer with proactive detection
  • Code Quality Metrics: Better with automated fixes

Master debugging with AI assistance:

  1. Enable YOLO mode for automated error fixing
  2. Set up error tracking integration
  3. Use bug finder before every commit
  4. Create debug templates for common issues
  5. Share debugging patterns with your team