debtmap 0.17.0

Code complexity and technical debt analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
# Error Handling Analysis

Debtmap provides comprehensive error handling analysis for Rust codebases, detecting anti-patterns that lead to silent failures, production panics, and difficult-to-debug issues.

## Implementation Status

| Language | Error Swallowing | Panic Patterns | Async Errors | Context Loss | Propagation Analysis |
|----------|------------------|----------------|--------------|--------------|----------------------|
| **Rust** | ✅ Full (7 patterns) | ✅ Full (6 patterns) | ✅ Full (5 patterns) | ✅ Full (5 patterns) | ✅ Full (4 patterns) |
| **Python** | ⚠️ Planned | ⚠️ Planned | N/A | ⚠️ Planned | ⚠️ Planned |
| **JavaScript/TypeScript** | ⚠️ Partial | N/A | ⚠️ Partial | ❌ Not yet | ❌ Not yet |

**Current Focus:** Rust error handling analysis is the most comprehensive. JavaScript and TypeScript include async debt detection for callback hell, unhandled promise chains, and long promise chains. Python error-specific analysis remains limited compared with Rust.

## Overview

Error handling issues are classified as **ErrorSwallowing** debt with **Major severity** (weight 4), reflecting their significant impact on code reliability and debuggability.

**Fully Implemented for Rust:**
- **Error swallowing** (7 patterns): Exception handlers that silently catch errors without logging or re-raising
- **Panic patterns** (6 patterns): Code that can panic in production (unwrap, expect, panic!)
- **Error propagation issues** (4 patterns): Missing error context in Result chains
- **Async error handling** (5 patterns): Dropped futures, unhandled JoinHandles, silent task panics
- **Context loss detection** (5 patterns): Error propagation without meaningful context

All error handling patterns are filtered intelligently - code detected in test modules (e.g., `#[cfg(test)]`, `#[test]` attributes) receives lower priority or is excluded entirely.

## Rust Error Handling Analysis

### Panic Pattern Detection

Debtmap identifies Rust code that can panic at runtime instead of returning `Result`:

**Detected patterns:**

```rust
// ❌ CRITICAL: Direct panic in production code
fn process_data(value: Option<i32>) -> i32 {
    panic!("not implemented");  // Detected: PanicInNonTest
}

// ❌ HIGH: Unwrap on Result
fn read_config(path: &Path) -> Config {
    let content = fs::read_to_string(path).unwrap();  // Detected: UnwrapOnResult
    parse_config(&content)
}

// ❌ HIGH: Unwrap on Option
fn get_user(id: u32) -> User {
    users.get(&id).unwrap()  // Detected: UnwrapOnOption
}

// ❌ MEDIUM: Expect with generic message
fn parse_value(s: &str) -> i32 {
    s.parse().expect("parse failed")  // Detected: ExpectWithGenericMessage
}

// ❌ MEDIUM: TODO in production
fn calculate_tax(amount: f64) -> f64 {
    todo!("implement tax calculation")  // Detected: TodoInProduction
}
```

**Recommended alternatives:**

```rust
// ✅ GOOD: Propagate errors with ?
fn read_config(path: &Path) -> Result<Config> {
    let content = fs::read_to_string(path)?;
    parse_config(&content)
}

// ✅ GOOD: Handle Option explicitly
fn get_user(id: u32) -> Result<User> {
    users.get(&id)
        .ok_or_else(|| anyhow!("User {} not found", id))
}

// ✅ GOOD: Add meaningful context
fn parse_value(s: &str) -> Result<i32> {
    s.parse()
        .with_context(|| format!("Failed to parse '{}' as integer", s))
}
```

**Test code exceptions:**

```rust
#[cfg(test)]
mod tests {
    #[test]
    fn test_parsing() {
        let result = "42".parse::<i32>().unwrap();  // ✅ OK in tests (LOW priority)
        assert_eq!(result, 42);
    }
}
```

Debtmap detects `#[cfg(test)]` attributes and test function contexts, automatically assigning **Low priority** to panic patterns in test code.

### Error Propagation Analysis

Debtmap detects missing error context in Result chains.

**Note:** Context loss detection uses AST-based heuristics without full type information. This means some edge cases may produce false positives or negatives. Type information would improve accuracy but would require a full compilation environment.

```rust
// ❌ Missing context - which file failed? What was the error?
fn load_multiple_configs(paths: &[PathBuf]) -> Result<Vec<Config>> {
    paths.iter()
        .map(|p| fs::read_to_string(p))  // Error loses file path information
        .collect::<Result<Vec<_>>>()?
        .into_iter()
        .map(|c| parse_config(&c))  // Error loses which config failed
        .collect()
}

// ✅ GOOD: Preserve context through the chain
fn load_multiple_configs(paths: &[PathBuf]) -> Result<Vec<Config>> {
    paths.iter()
        .map(|p| {
            fs::read_to_string(p)
                .with_context(|| format!("Failed to read config from {}", p.display()))
        })
        .collect::<Result<Vec<_>>>()?
        .into_iter()
        .enumerate()
        .map(|(i, content)| {
            parse_config(&content)
                .with_context(|| format!("Failed to parse config #{}", i))
        })
        .collect()
}
```

**Best practices:**
- Use `.context()` or `.with_context()` from `anyhow` or `thiserror`
- Include relevant values in error messages (file paths, indices, input values)
- Maintain error context at each transformation in the chain

### Error Swallowing in Rust

Debtmap detects seven distinct patterns of error swallowing in Rust, where errors are silently ignored without logging or propagation:

#### 1. IfLetOkNoElse - Missing else branch

```rust
// ❌ Detected: if let Ok without else branch
fn try_update(value: &str) {
    if let Ok(parsed) = value.parse::<i32>() {
        update_value(parsed);
    }
    // Error case silently ignored - no logging or handling
}

// ✅ GOOD: Handle both cases
fn try_update(value: &str) -> Result<()> {
    if let Ok(parsed) = value.parse::<i32>() {
        update_value(parsed);
        Ok(())
    } else {
        Err(anyhow!("Failed to parse value: {}", value))
    }
}
```

#### 2. IfLetOkEmptyElse - Empty else branch

```rust
// ❌ Detected: if let Ok with empty else
fn process_result(result: Result<Data, Error>) {
    if let Ok(data) = result {
        process(data);
    } else {
        // Empty else - error silently swallowed
    }
}

// ✅ GOOD: Log the error
fn process_result(result: Result<Data, Error>) {
    if let Ok(data) = result {
        process(data);
    } else {
        log::error!("Failed to process: {:?}", result);
    }
}
```

#### 3. LetUnderscoreResult - Discarding Result with let _

```rust
// ❌ Detected: Result discarded with let _
fn save_data(data: &Data) {
    let _ = fs::write("data.json", serde_json::to_string(data).unwrap());
    // Write failure silently ignored
}

// ✅ GOOD: Handle or propagate the error
fn save_data(data: &Data) -> Result<()> {
    fs::write("data.json", serde_json::to_string(data)?)
        .context("Failed to save data")?;
    Ok(())
}
```

#### 4. OkMethodDiscard - Calling .ok() and discarding

```rust
// ❌ Detected: .ok() called but result discarded
fn try_parse(s: &str) -> Option<i32> {
    s.parse::<i32>().ok();  // Result immediately discarded
    None
}

// ✅ GOOD: Use the Ok value or log the error
fn try_parse(s: &str) -> Option<i32> {
    match s.parse::<i32>() {
        Ok(v) => Some(v),
        Err(e) => {
            log::warn!("Failed to parse '{}': {}", s, e);
            None
        }
    }
}
```

#### 5. MatchIgnoredErr - Match with ignored error variant

```rust
// ❌ Detected: match with _ in Err branch
fn try_load(path: &Path) -> Option<String> {
    match fs::read_to_string(path) {
        Ok(content) => Some(content),
        Err(_) => None,  // Error details ignored
    }
}

// ✅ GOOD: Log the error with context
fn try_load(path: &Path) -> Option<String> {
    match fs::read_to_string(path) {
        Ok(content) => Some(content),
        Err(e) => {
            log::error!("Failed to read {}: {}", path.display(), e);
            None
        }
    }
}
```

#### 6. UnwrapOrNoLog - .unwrap_or() without logging

```rust
// ❌ Detected: unwrap_or without logging
fn get_config_value(key: &str) -> String {
    load_config()
        .and_then(|c| c.get(key))
        .unwrap_or_else(|| "default".to_string())
    // Error silently replaced with default
}

// ✅ GOOD: Log before falling back to default
fn get_config_value(key: &str) -> String {
    match load_config().and_then(|c| c.get(key)) {
        Ok(value) => value,
        Err(e) => {
            log::warn!("Config key '{}' not found: {}. Using default.", key, e);
            "default".to_string()
        }
    }
}
```

#### 7. UnwrapOrDefaultNoLog - .unwrap_or_default() without logging

```rust
// ❌ Detected: unwrap_or_default without logging
fn load_settings() -> Settings {
    read_settings_file().unwrap_or_default()
    // Error silently replaced with default settings
}

// ✅ GOOD: Log the fallback to defaults
fn load_settings() -> Settings {
    match read_settings_file() {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to load settings: {}. Using defaults.", e);
            Settings::default()
        }
    }
}
```

**Summary of Error Swallowing Patterns:**

| Pattern | Description | Common Cause |
|---------|-------------|--------------|
| IfLetOkNoElse | `if let Ok(..)` without else | Quick prototyping, forgotten error path |
| IfLetOkEmptyElse | `if let Ok(..)` with empty else | Incomplete implementation |
| LetUnderscoreResult | `let _ = result` | Intentional ignore without thought |
| OkMethodDiscard | `.ok()` result not used | Misunderstanding of .ok() semantics |
| MatchIgnoredErr | `Err(_) => ...` with no logging | Generic error handling |
| UnwrapOrNoLog | `.unwrap_or()` without logging | Convenience over observability |
| UnwrapOrDefaultNoLog | `.unwrap_or_default()` without logging | Default fallback without visibility |

All these patterns are detected at **Medium to High priority** depending on context, as they represent lost error information that makes debugging difficult.

**Source:** Error swallowing patterns are defined in `src/debt/error_swallowing.rs:234-243` and comprehensively tested in `tests/error_swallowing_test.rs`.

## Python Error Handling Analysis (Planned)

⚠️ **Python error handling detection is planned but not yet implemented. Currently only Rust error patterns are fully supported.**

The patterns described below represent the intended future behavior once Python analysis is implemented.

### Bare Except Clause Detection (Planned)

Python's bare `except:` catches all exceptions, including system exits and keyboard interrupts:

```python
# ❌ CRITICAL: Bare except catches everything
def process_file(path):
    try:
        with open(path) as f:
            return f.read()
    except:  # Detected: BareExceptClause
        return None  # Catches SystemExit, KeyboardInterrupt, etc.

# ❌ HIGH: Catching Exception is too broad
def load_config(path):
    try:
        return yaml.load(open(path))
    except Exception:  # Detected: OverlyBroadException
        return {}  # Silent failure loses error information

# ✅ GOOD: Specific exception types
def process_file(path):
    try:
        with open(path) as f:
            return f.read()
    except FileNotFoundError:
        log.error(f"File not found: {path}")
        return None
    except PermissionError:
        log.error(f"Permission denied: {path}")
        return None
```

**Why bare except is dangerous:**
- Catches `SystemExit` (prevents clean shutdown)
- Catches `KeyboardInterrupt` (prevents Ctrl+C)
- Catches `GeneratorExit` (breaks generator protocol)
- Masks programming errors like `NameError`, `AttributeError`

**Best practices:**
- Always specify exception types: `except ValueError`, `except (TypeError, KeyError)`
- Use `except Exception` only when truly catching all application errors
- Never use bare `except:` in production code
- Log exceptions with full context before suppressing

### Silent Exception Handling (Planned)

```python
# ❌ Silent exception handling
def get_user_age(user_id):
    try:
        user = db.get_user(user_id)
        return user.age
    except:  # Detected: SilentException (no logging, no re-raise)
        pass

# ✅ GOOD: Log and provide meaningful default
def get_user_age(user_id):
    try:
        user = db.get_user(user_id)
        return user.age
    except UserNotFound:
        logger.warning(f"User {user_id} not found")
        return None
    except DatabaseError as e:
        logger.error(f"Database error fetching user {user_id}: {e}")
        raise  # Re-raise for caller to handle
```

### Contextlib Suppress Detection (Planned)

Python's `contextlib.suppress()` intentionally silences exceptions, which can hide errors:

```python
from contextlib import suppress

# ❌ MEDIUM: contextlib.suppress hides errors
def cleanup_temp_files(paths):
    for path in paths:
        with suppress(FileNotFoundError, PermissionError):
            os.remove(path)  # Detected: ContextlibSuppress
            # Errors silently suppressed - no visibility into failures

# ✅ GOOD: Log suppressed errors
def cleanup_temp_files(paths):
    for path in paths:
        try:
            os.remove(path)
        except FileNotFoundError:
            logger.debug(f"File already deleted: {path}")
        except PermissionError as e:
            logger.warning(f"Permission denied removing {path}: {e}")
        except Exception as e:
            logger.error(f"Unexpected error removing {path}: {e}")

# ✅ ACCEPTABLE: Use suppress only for truly ignorable cases
def best_effort_cleanup(paths):
    """Best-effort cleanup - failures are expected and acceptable."""
    for path in paths:
        with suppress(OSError):  # OK if documented and intentional
            os.remove(path)
```

**When contextlib.suppress is acceptable:**
- Cleanup operations where failures are genuinely unimportant
- Operations explicitly documented as "best effort"
- Code where logging would create noise without value

**When to avoid contextlib.suppress:**
- Production code where error visibility matters
- Operations where partial failure should be noticed
- Any case where debugging might be needed later

### Exception Flow Analysis (Planned)

Python exception flow analysis is planned for future implementation. This would track exception propagation through Python codebases to identify functions that can raise exceptions without proper handling.

```python
# Potential issue: Exceptions may propagate unhandled
def process_batch(items):
    for item in items:
        validate_item(item)  # Can raise ValueError
        transform_item(item)  # Can raise TransformError
        save_item(item)  # Can raise DatabaseError

# ✅ GOOD: Handle exceptions appropriately
def process_batch(items):
    results = {"success": 0, "failed": 0}
    for item in items:
        try:
            validate_item(item)
            transform_item(item)
            save_item(item)
            results["success"] += 1
        except ValueError as e:
            logger.warning(f"Invalid item {item.id}: {e}")
            results["failed"] += 1
        except (TransformError, DatabaseError) as e:
            logger.error(f"Failed to process item {item.id}: {e}")
            results["failed"] += 1
            # Optionally re-raise critical errors
            if isinstance(e, DatabaseError):
                raise
    return results
```

## Async Error Handling

### JavaScript/TypeScript Async Patterns

⚠️ **JavaScript and TypeScript async error detection is partially implemented.**

**Current Status:**
- JavaScript/TypeScript support includes callback hell, unhandled promise chains, and long promise chains
- Rust remains the most comprehensive implementation for async error handling
- Context-loss and propagation analysis are still Rust-focused

The examples below show the kinds of async issues debtmap is intended to surface:

```javascript
// ❌ CRITICAL: Unhandled promise rejection
async function loadUserData(userId) {
    const response = await fetch(`/api/users/${userId}`);
    // If fetch rejects, promise is unhandled
    return response.json();
}

loadUserData(123);  // Detected: UnhandledPromiseRejection

// ✅ GOOD: Handle rejections
async function loadUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return await response.json();
    } catch (error) {
        console.error(`Failed to load user ${userId}:`, error);
        throw error;  // Re-throw or return default
    }
}

loadUserData(123).catch(err => {
    console.error("Top-level error handler:", err);
});
```

### Missing Await Detection (Planned)

```javascript
// ❌ HIGH: Missing await - promise dropped
async function saveAndNotify(data) {
    await saveToDatabase(data);
    sendNotification(data.userId);  // Detected: MissingAwait
    // Function returns before notification completes
}

// ✅ GOOD: Await all async operations
async function saveAndNotify(data) {
    await saveToDatabase(data);
    await sendNotification(data.userId);
}
```

### Async Rust Error Handling

Debtmap detects five async-specific error handling patterns in Rust.

**Note:** Async error detection uses pattern matching on tokio APIs and AST-based heuristics. Some patterns (particularly `select!` macro handling and future dropping) may require manual review, as full semantic analysis would require type information.

#### 1. DroppedFuture - Future dropped without awaiting

```rust
// ❌ HIGH: Dropped future without error handling
async fn process_requests(requests: Vec<Request>) {
    for req in requests {
        tokio::spawn(async move {
            handle_request(req).await  // Detected: DroppedFuture
            // Errors silently dropped
        });
    }
}

// ✅ GOOD: Join handles and propagate errors
async fn process_requests(requests: Vec<Request>) -> Result<()> {
    let handles: Vec<_> = requests.into_iter()
        .map(|req| {
            tokio::spawn(async move {
                handle_request(req).await
            })
        })
        .collect();

    for handle in handles {
        handle.await??;  // Propagate both JoinError and handler errors
    }
    Ok(())
}
```

#### 2. UnhandledJoinHandle - Spawned task without join

```rust
// ❌ HIGH: Task spawned but handle never checked
async fn background_sync() {
    tokio::spawn(async {
        sync_to_database().await  // Detected: UnhandledJoinHandle
    });
    // Handle dropped - can't detect if task panicked or failed
}

// ✅ GOOD: Store and check join handle
async fn background_sync() -> Result<()> {
    let handle = tokio::spawn(async {
        sync_to_database().await
    });
    handle.await?  // Wait for completion and check for panic
}
```

#### 3. SilentTaskPanic - Task panic without monitoring

```rust
// ❌ HIGH: Task panic silently ignored
tokio::spawn(async {
    panic!("task failed");  // Detected: SilentTaskPanic
});

// ✅ GOOD: Handle task panics
let handle = tokio::spawn(async {
    critical_operation().await
});

match handle.await {
    Ok(Ok(result)) => println!("Success: {:?}", result),
    Ok(Err(e)) => eprintln!("Task failed: {}", e),
    Err(e) => eprintln!("Task panicked: {}", e),
}
```

#### 4. SpawnWithoutJoin - Spawning without storing handle

```rust
// ❌ MEDIUM: Spawn without storing handle
async fn fire_and_forget_tasks(items: Vec<Item>) {
    for item in items {
        tokio::spawn(process_item(item));  // Detected: SpawnWithoutJoin
        // No way to check task completion or errors
    }
}

// ✅ GOOD: Collect handles for later checking
async fn process_tasks_with_monitoring(items: Vec<Item>) -> Result<()> {
    let handles: Vec<_> = items.into_iter()
        .map(|item| tokio::spawn(process_item(item)))
        .collect();

    for handle in handles {
        handle.await??;
    }
    Ok(())
}
```

#### 5. SelectBranchIgnored - Select branch without error handling

```rust
// ❌ MEDIUM: tokio::select! branch error ignored
async fn process_with_timeout(data: Data) {
    tokio::select! {
        result = process_data(data) => {
            // Detected: SelectBranchIgnored
            // result could be Err but not checked
        }
        _ = tokio::time::sleep(Duration::from_secs(5)) => {
            println!("Timeout");
        }
    }
}

// ✅ GOOD: Handle errors in select branches
async fn process_with_timeout(data: Data) -> Result<()> {
    tokio::select! {
        result = process_data(data) => {
            result?;  // Propagate error
            Ok(())
        }
        _ = tokio::time::sleep(Duration::from_secs(5)) => {
            Err(anyhow!("Processing timeout after 5s"))
        }
    }
}
```

**Async Error Pattern Summary:**

| Pattern | Severity | Description | Common in |
|---------|----------|-------------|-----------|
| DroppedFuture | High | Future result ignored | Fire-and-forget spawns |
| UnhandledJoinHandle | High | JoinHandle never checked | Background tasks |
| SilentTaskPanic | High | Task panic not monitored | Unmonitored spawns |
| SpawnWithoutJoin | Medium | Handle not stored | Quick prototypes |
| SelectBranchIgnored | Medium | select! branch error ignored | Concurrent operations |

All async error patterns emphasize the importance of properly handling errors in concurrent Rust code, where failures can easily go unnoticed.

**Source:** Async error patterns are defined in `src/debt/async_errors.rs:210-217` and tested with tokio-specific patterns.

## Severity Levels and Prioritization

Error handling issues are assigned severity based on their impact:

| Pattern | Severity | Weight | Priority | Rationale |
|---------|----------|--------|----------|-----------|
| Panic in production | CRITICAL | 4 | Critical | Crashes the process |
| Bare except clause | CRITICAL | 4 | Critical | Masks system signals |
| Silent task panic | CRITICAL | 4 | Critical | Hidden failures |
| Unwrap on Result/Option | HIGH | 4 | High | Likely to panic |
| Dropped future | HIGH | 4 | High | Lost error information |
| Unhandled promise rejection | HIGH | 4 | High | Silently fails |
| Error swallowing | MEDIUM | 4 | Medium | Loses debugging context |
| Missing error context | MEDIUM | 4 | Medium | Hard to debug |
| Expect with generic message | MEDIUM | 4 | Medium | Uninformative errors |
| TODO in production | MEDIUM | 4 | Medium | Incomplete implementation |

All ErrorSwallowing debt has **weight 4** (Major severity), but individual patterns receive different priorities based on production impact.

### Integration with Risk Scoring

Error handling issues contribute to the `debt_factor` in Debtmap's risk scoring formula:

```
risk_score = (complexity_factor * 0.4) + (debt_factor * 0.3) + (coverage_factor * 0.3)

where debt_factor includes:
- ErrorSwallowing count * weight (4)
- Combined with other debt types
```

**Compound risk example:**

```rust
// HIGH RISK: High complexity + error swallowing + low coverage
fn process_transaction(tx: Transaction) -> bool {  // Cyclomatic: 12, Cognitive: 18
    if tx.amount > 1000 {
        if tx.verified {
            if validate_funds(&tx).unwrap() {  // ❌ Panic pattern
                if tx.user_type == "premium" {
                    match apply_premium_discount(&tx) {
                        Ok(_) => {},
                        Err(_) => return false,  // ❌ Error swallowed
                    }
                }
                charge_account(&tx).unwrap();  // ❌ Another panic
                return true;
            }
        }
    }
    false
}
// Coverage: 45% (untested error paths)
// Risk Score: Very High (complexity + error handling + coverage gaps)
```

This function would be flagged as **Priority 1** in Debtmap's output due to:
- High cyclomatic complexity (12)
- Multiple panic patterns (unwrap calls)
- Error swallowing (ignored Result)
- Coverage gaps in error handling paths

## Configuration

### Error Handling Configuration Options

**All Rust error handling detection is enabled by default.** You typically don't need to configure anything - Debtmap will automatically detect all error patterns in your Rust code.

**When to Use Configuration:**
- **Gradual adoption**: Disable some patterns while fixing others
- **Project-specific needs**: Turn off patterns that don't apply to your codebase
- **Performance tuning**: Disable expensive analyzers if not needed

Configure error handling analysis in `.debtmap.toml`:

```toml
[error_handling]
# All patterns enabled by default - only add config to DISABLE patterns
# detect_panic_patterns = true     # Default: enabled
# detect_swallowing = true          # Default: enabled
# detect_async_errors = true        # Default: enabled
# detect_context_loss = true        # Default: enabled
# detect_propagation = true         # Default: enabled

# Example: Gradual adoption - start with just panic patterns
detect_panic_patterns = true       # Keep enabled
detect_swallowing = false          # Disable initially
detect_async_errors = false        # Disable initially
detect_context_loss = false        # Disable initially
```

**Default Behavior (No Configuration):**
All error handling patterns are detected with the `ErrorSwallowing` debt category (weight 4). Test code automatically receives lower priority.

## Detection Examples

### What Gets Detected vs. Not Detected

#### Rust Examples (Fully Implemented)

```rust
// ❌ Detected: unwrap() in production code
pub fn get_config() -> Config {
    load_config().unwrap()
}

// ✅ Not detected: ? operator (proper error propagation)
pub fn get_config() -> Result<Config> {
    load_config()?
}

// ✅ Not detected: unwrap() in test
#[test]
fn test_config() {
    let config = load_config().unwrap();  // OK in tests
    assert_eq!(config.port, 8080);
}

// ❌ Detected: expect() with generic message
let value = map.get("key").expect("missing");

// ✅ Not detected: expect() with descriptive context
let value = map.get("key")
    .expect("Configuration must contain 'key' field");
```

#### Python Examples (Planned - Not Yet Implemented)

```python
# ❌ Detected: bare except
try:
    risky_operation()
except:
    pass

# ✅ Not detected: specific exception
try:
    risky_operation()
except ValueError:
    handle_value_error()

# ❌ Detected: silent exception (no logging/re-raise)
try:
    db.save(record)
except DatabaseError:
    pass  # Silent failure

# ✅ Not detected: logged exception
try:
    db.save(record)
except DatabaseError as e:
    logger.error(f"Failed to save record: {e}")
    raise
```

## Suppression Patterns

For cases where error handling patterns are intentional, use suppression comments:

**Rust:**

```rust
// debtmap: ignore - Unwrap is safe here due to prior validation
let value = validated_map.get("key").unwrap();
```

**Python:**

```python
try:
    experimental_feature()
except:  # debtmap: ignore - Intentional catch-all during migration
    use_fallback()
```

See [Suppression Patterns](suppression-patterns.md) for complete syntax and usage.

## Best Practices

### Rust Error Handling

1. **Prefer `?` operator over unwrap/expect**
   ```rust
   // Instead of: fs::read_to_string(path).unwrap()
   // Use: fs::read_to_string(path)?
   ```

2. **Use anyhow for application errors, thiserror for libraries**
   ```rust
   use anyhow::{Context, Result};

   fn load_data(path: &Path) -> Result<Data> {
       let content = fs::read_to_string(path)
           .with_context(|| format!("Failed to read {}", path.display()))?;
       parse_data(&content)
           .context("Invalid data format")
   }
   ```

3. **Add context at each error boundary**
   ```rust
   .with_context(|| format!("meaningful message with {}", value))
   ```

4. **Handle Option explicitly**
   ```rust
   map.get(key).ok_or_else(|| anyhow!("Missing key: {}", key))?
   ```

### Python Error Handling (Planned - Future Implementation)

**Note:** Python error handling detection is planned. These best practices represent intended future behavior.

1. **Always use specific exception types**
   ```python
   except (ValueError, KeyError) as e:
   ```

2. **Log before suppressing**
   ```python
   except DatabaseError as e:
       logger.error(f"Database operation failed: {e}", exc_info=True)
       # Then decide: re-raise, return default, or handle
   ```

3. **Avoid bare except completely**
   ```python
   # If you must catch everything:
   except Exception as e:  # Not bare except:
       logger.exception("Unexpected error")
       raise
   ```

4. **Use context managers for resource cleanup**
   ```python
   with open(path) as f:  # Ensures cleanup even on exception
       process(f)
   ```

### JavaScript/TypeScript Error Handling (Planned - Limited Implementation)

**Note:** JavaScript/TypeScript async error detection is planned. Currently only basic patterns are supported.

1. **Always handle promise rejections**
   ```javascript
   fetchData().catch(err => console.error(err));
   // Or use try/catch with async/await
   ```

2. **Use async/await consistently**
   ```javascript
   async function process() {
       try {
           const data = await fetchData();
           await saveData(data);
       } catch (error) {
           console.error("Failed:", error);
           throw error;
       }
   }
   ```

3. **Don't forget await**
   ```javascript
   await asyncOperation();  // Don't drop promises
   ```

## Improving Rust Error Handling Based on Debtmap Reports

### Workflow

1. **Run analysis with error focus**
   ```bash
   debtmap analyze . --filter ErrorHandling
   ```

   Note: This analyzes Rust error patterns. Python and JavaScript/TypeScript support is limited or planned.

2. **Review priority issues first**
   - Address CRITICAL (panic in production, bare except) immediately
   - Schedule HIGH (unwrap, dropped futures) for next sprint
   - Plan MEDIUM (missing context) for gradual improvement

3. **Fix systematically**
   - One file or module at a time
   - Add tests as you improve error handling
   - Run debtmap after each fix to verify

4. **Validate improvements**
   ```bash
   # Before fixes
   debtmap analyze . --format json --output before.json

   # After fixes
   debtmap analyze . --format json --output after.json

   # Compare
   debtmap compare --before before.json --after after.json
   ```

### Migration Strategy for Legacy Code

```toml
# .debtmap.toml - Gradual adoption
[error_handling]
# Start with just critical panic patterns
detect_panic_patterns = true
detect_swallowing = false      # Add later
detect_async_errors = false    # Add later
detect_context_loss = false    # Add later

# After fixing panic patterns, enable error swallowing detection
# detect_swallowing = true

# Eventually enable all patterns
# detect_swallowing = true
# detect_async_errors = true
# detect_context_loss = true
# detect_propagation = true
```

Track progress over time:
```bash
# Weekly error handling health check
debtmap analyze . --filter ErrorHandling | tee weekly-error-health.txt
```

## Troubleshooting

### Too Many False Positives in Test Code

**Problem:** Debtmap flagging `unwrap()` in test functions

**Solution:** Debtmap should automatically detect test code via:
- `#[cfg(test)]` modules in Rust
- `#[test]` attributes
- `test_` function name prefix in Python
- `*.test.ts`, `*.spec.js` file patterns

If false positives persist:
```rust
// Use suppression comment
let value = result.unwrap();  // debtmap: ignore - Test assertion
```

### Error Patterns Not Being Detected

**Problem:** Known error patterns not appearing in report

**Causes and solutions:**

1. **Language support not enabled**
   ```bash
   debtmap analyze . --languages rust,python,javascript,typescript
   ```

2. **Pattern disabled in config**
   ```toml
   [error_handling]
   detect_panic_patterns = true
   detect_swallowing = true
   detect_async_errors = true  # Ensure relevant detectors are enabled
   ```

3. **Suppression comment present**
   - Check for `debtmap: ignore` comments
   - Review `.debtmap.toml` ignore patterns

### Disagreement with Severity Levels

**Problem:** Severity feels too high/low for your codebase

**Solution:** Customize in `.debtmap.toml`:

```toml
[debt_categories.ErrorSwallowing]
weight = 2  # Reduce from default 4 to Warning level
severity = "Warning"

# Or increase for stricter enforcement
# weight = 5
# severity = "Critical"
```

### Can't Find Which Line Has the Issue

**Problem:** Debtmap reports error at wrong line number

**Causes:**
- Source code changed since analysis
- Parser approximation for line numbers

**Solutions:**
1. Re-run analysis: `debtmap analyze`
2. Search for pattern: `rg "\.unwrap\(\)" src/`
3. Use verbose diagnostics: `debtmap analyze . -vv`

### Validating Error Handling Improvements

**Problem:** Unsure if fixes actually improved code quality

**Solution:** Use compare workflow:

```bash
# Baseline before fixes
git checkout main
debtmap analyze . --format json --output baseline.json

# After fixes
git checkout feature/improve-errors
debtmap analyze . --format json --output improved.json

# Compare reports
debtmap compare --before baseline.json --after improved.json
```

Look for:
- Reduced ErrorSwallowing debt count
- Lower risk scores for affected functions
- Improved coverage of error paths (if running with coverage)

## Related Topics

- [Configuration]configuration.md - Complete `.debtmap.toml` reference
- [Suppression Patterns]suppression-patterns.md - Suppress false positives
- [Scoring Strategies]scoring-strategies.md - How error handling affects risk scores
- [Coverage Integration]coverage-integration.md - Detect untested error paths
- [CLI Reference]cli-reference.md - Command-line options for error analysis
- [Troubleshooting]troubleshooting.md - General debugging guide