-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgo-avoid-panic.mdc
More file actions
75 lines (59 loc) · 2.09 KB
/
go-avoid-panic.mdc
File metadata and controls
75 lines (59 loc) · 2.09 KB
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
---
description: "Eliminate `panic()` calls by converting them into error returns with static error values."
globs: *.go, pkg/**/*.go
alwaysApply: true
---
# Panic-to-Error Refactoring Rule
**Problem:** Uncontrolled `panic()` calls crash applications and bypass usual error handling. We need to replace panics with returned errors to allow graceful handling.
## Rule
1. **Static Error Declarations**
* Define all error values in a shared `var` block, using `errors.New(...)` with a clear, unique message.
* Prefix error strings with the package or function name for clarity.
```go
var (
ParseConfigError = errors.New("config: parse error")
InvalidInputError = errors.New("input: invalid parameter")
)
```
2. **Convert `panic()` to Error Return**
* Remove `panic(err)` or `panic("message")` calls.
* Insert a `DebugLog` (or equivalent logger) statement to record dynamic details.
* Change the function signature to return `error` (or add `error` to returns).
* Return the appropriate static error after logging.
## Examples
### \[FAIL] Panic Usage
```go
func LoadConfig(path string) *Config {
data, err := os.ReadFile(path)
if err != nil {
panic(err)
}
// ... parse data ...
if missingField {
panic("missing required field: name")
}
return cfg
}
```
### \[OK] Error Return
```go
func LoadConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
i.DebugLog("LoadConfig: failed to read file %s: %v", path, err)
return nil, ParseConfigError
}
// ... parse data ...
if missingField {
i.DebugLog("LoadConfig: missing required field 'name'")
return nil, InvalidInputError
}
return cfg, nil
}
```
## Notes
* **Preserve dynamic details** in logs, not in error strings.
* **Always return** errors instead of panicking.
* **Update callers** to handle the new `error` return value.
* **Function signatures** must include `error` if they currently do not.
*Apply this rule to all Go packages to ensure predictable error handling and avoid unexpected panics.*