@esreekarreddy/ai-prompts 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +361 -0
- package/chains/_index.md +33 -0
- package/chains/bug-fix.md +222 -0
- package/chains/new-feature.md +216 -0
- package/chains/production-launch.md +291 -0
- package/chains/refactor.md +210 -0
- package/chains/security-hardening.md +242 -0
- package/contexts/guides/api-design.md +229 -0
- package/contexts/guides/error-handling.md +219 -0
- package/contexts/patterns/agentic-coding.md +368 -0
- package/contexts/patterns/mcp-server-patterns.md +267 -0
- package/contexts/patterns/repository-pattern.md +163 -0
- package/contexts/patterns/service-layer.md +185 -0
- package/contexts/stacks/fastapi.md +187 -0
- package/contexts/stacks/nextjs-14.md +149 -0
- package/contexts/stacks/prisma.md +228 -0
- package/dist/index.d.ts +129 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +284 -0
- package/dist/index.js.map +1 -0
- package/examples/architecture-docs/sample-architecture.md +270 -0
- package/examples/code-reviews/sample-review.md +232 -0
- package/examples/prds/sample-prd.md +179 -0
- package/instructions/_index.md +57 -0
- package/instructions/personas/code-reviewer.md +83 -0
- package/instructions/personas/devops-engineer.md +90 -0
- package/instructions/personas/security-expert.md +69 -0
- package/instructions/personas/senior-engineer.md +243 -0
- package/instructions/personas/ux-engineer.md +88 -0
- package/instructions/standards/fastapi.md +241 -0
- package/instructions/standards/go.md +427 -0
- package/instructions/standards/nextjs.md +350 -0
- package/instructions/standards/nodejs.md +284 -0
- package/instructions/standards/python.md +245 -0
- package/instructions/standards/react.md +227 -0
- package/instructions/standards/rust.md +318 -0
- package/instructions/standards/typescript-react.md +822 -0
- package/instructions/standards/typescript.md +294 -0
- package/instructions/workflows/feature-development.md +222 -0
- package/instructions/workflows/incident-response.md +192 -0
- package/instructions/workflows/pr-review.md +149 -0
- package/instructions/workflows/tdd.md +160 -0
- package/package.json +84 -0
- package/prompts/_index.md +70 -0
- package/prompts/agentic/agentic-loop.md +83 -0
- package/prompts/agentic/context-manager.md +37 -0
- package/prompts/agentic/test-driven-fix.md +41 -0
- package/prompts/analysis/deep-debugger.md +488 -0
- package/prompts/design/design-system-extractor.md +147 -0
- package/prompts/development/code-cleaner.md +119 -0
- package/prompts/development/debugger.md +64 -0
- package/prompts/development/tech-debt-audit.md +88 -0
- package/prompts/planning/architecture-analyzer.md +72 -0
- package/prompts/planning/implementation-plan.md +98 -0
- package/prompts/planning/prd-generator.md +66 -0
- package/prompts/planning/scope-killer.md +74 -0
- package/prompts/quality/critical-path-tester.md +133 -0
- package/prompts/quality/pre-launch-checklist.md +137 -0
- package/prompts/quality/security-audit.md +115 -0
- package/prompts/quality/security-fixer.md +117 -0
- package/prompts/quality/security-hardening.md +157 -0
- package/prompts/system/master-system-prompt.md +252 -0
- package/skills/_index.md +60 -0
- package/skills/code-review-advanced.md +435 -0
- package/skills/code-review.md +86 -0
- package/skills/debugging.md +86 -0
- package/skills/documentation.md +97 -0
- package/skills/pr-description.md +116 -0
- package/skills/project-setup.md +123 -0
- package/skills/refactoring.md +93 -0
- package/skills/testing.md +134 -0
- package/snippets/_index.md +57 -0
- package/snippets/constraints/mvp-only.md +50 -0
- package/snippets/constraints/no-external-deps.md +45 -0
- package/snippets/constraints/read-only.md +45 -0
- package/snippets/constraints/security-first.md +50 -0
- package/snippets/modifiers/be-ruthless.md +52 -0
- package/snippets/modifiers/be-thorough.md +50 -0
- package/snippets/modifiers/effort-high.md +56 -0
- package/snippets/modifiers/explain-reasoning.md +50 -0
- package/snippets/modifiers/megathink.md +314 -0
- package/snippets/modifiers/meta-cot.md +101 -0
- package/snippets/modifiers/no-code-yet.md +55 -0
- package/snippets/modifiers/step-by-step.md +50 -0
- package/snippets/modifiers/ultrathink.md +359 -0
- package/snippets/output-formats/checklist.md +61 -0
- package/snippets/output-formats/json.md +53 -0
- package/snippets/output-formats/markdown-table.md +44 -0
- package/snippets/output-formats/numbered-list.md +44 -0
- package/templates/_index.md +101 -0
- package/templates/claude-md/auto-enhance.md +258 -0
- package/templates/claude-md/cli-tool.md +243 -0
- package/templates/claude-md/full.md +449 -0
- package/templates/claude-md/minimal.md +52 -0
- package/templates/claude-md/nextjs-app.md +207 -0
- package/templates/claude-md/nodejs-service.md +251 -0
- package/templates/claude-md/python-api.md +236 -0
- package/templates/copilot/instructions.md +33 -0
- package/templates/cursor-rules/fullstack.txt +98 -0
- package/templates/cursor-rules/minimal.txt +20 -0
- package/templates/cursor-rules/nextjs.txt +61 -0
- package/templates/cursor-rules/python.txt +79 -0
- package/templates/docs/adr-template.md +119 -0
- package/templates/docs/api-spec-template.md +277 -0
- package/templates/docs/prd-template.md +140 -0
- package/templates/docs/runbook-template.md +238 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
# Chain: Security Hardening
|
|
2
|
+
|
|
3
|
+
> Comprehensive workflow for securing an application
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
Audit → Prioritize → Fix → Verify → Monitor
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Step 1: Security Audit
|
|
14
|
+
|
|
15
|
+
**Prompt:**
|
|
16
|
+
```
|
|
17
|
+
Security audit this codebase.
|
|
18
|
+
|
|
19
|
+
Check for:
|
|
20
|
+
|
|
21
|
+
1. Injection: SQL injection, command injection, XSS
|
|
22
|
+
2. Auth: Hardcoded secrets, weak passwords, missing rate limiting, non-expiring sessions
|
|
23
|
+
3. Authorization: IDOR, missing auth checks, bypassable role checks
|
|
24
|
+
4. Data exposure: Sensitive data in logs, stack traces to users, PII leaks
|
|
25
|
+
5. Config: Debug mode, permissive CORS, missing security headers
|
|
26
|
+
|
|
27
|
+
For each issue: severity (critical/high/medium/low), file/line, how to exploit, how to fix with code.
|
|
28
|
+
|
|
29
|
+
Be thorough. Ultrathink.
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
**Expected Output:**
|
|
33
|
+
- Comprehensive issue list
|
|
34
|
+
- Severity ratings
|
|
35
|
+
- Exploitation details
|
|
36
|
+
- Fix recommendations
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Step 2: Prioritize Fixes
|
|
41
|
+
|
|
42
|
+
**Prompt:**
|
|
43
|
+
```
|
|
44
|
+
Based on the security audit, help me prioritize:
|
|
45
|
+
|
|
46
|
+
Issues found:
|
|
47
|
+
[List issues]
|
|
48
|
+
|
|
49
|
+
For each severity:
|
|
50
|
+
1. Critical: Must fix immediately, could be actively exploited
|
|
51
|
+
2. High: Fix this sprint, significant risk
|
|
52
|
+
3. Medium: Plan to fix soon
|
|
53
|
+
4. Low: Address opportunistically
|
|
54
|
+
|
|
55
|
+
Also consider:
|
|
56
|
+
- Dependencies between fixes
|
|
57
|
+
- Quick wins vs. major changes
|
|
58
|
+
- External exposure (public vs. internal)
|
|
59
|
+
|
|
60
|
+
Create a prioritized action plan.
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
**Expected Output:**
|
|
64
|
+
- Prioritized fix order
|
|
65
|
+
- Timeline recommendations
|
|
66
|
+
- Dependencies noted
|
|
67
|
+
|
|
68
|
+
**Decision Point:** Agree on priority and timeline.
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Step 3: Fix Critical Issues
|
|
73
|
+
|
|
74
|
+
**Prompt:**
|
|
75
|
+
```
|
|
76
|
+
Fix this critical security issue:
|
|
77
|
+
|
|
78
|
+
Issue: [Issue details]
|
|
79
|
+
Location: [File and line]
|
|
80
|
+
Exploitation: [How it could be exploited]
|
|
81
|
+
|
|
82
|
+
Requirements:
|
|
83
|
+
1. Completely eliminate the vulnerability
|
|
84
|
+
2. Don't break existing functionality
|
|
85
|
+
3. Add test to prevent regression
|
|
86
|
+
4. Follow security best practices
|
|
87
|
+
|
|
88
|
+
Show the fix and explain why it's secure.
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Expected Output:**
|
|
92
|
+
- Security fix
|
|
93
|
+
- Explanation
|
|
94
|
+
- Regression test
|
|
95
|
+
|
|
96
|
+
**Repeat** for each critical/high issue.
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## Step 4: Add Security Controls
|
|
101
|
+
|
|
102
|
+
**Prompt:**
|
|
103
|
+
```
|
|
104
|
+
Beyond fixing specific issues, add these security controls:
|
|
105
|
+
|
|
106
|
+
1. Rate limiting on sensitive endpoints
|
|
107
|
+
2. Input validation on all user input
|
|
108
|
+
3. Security headers (CSP, HSTS, X-Frame-Options)
|
|
109
|
+
4. Proper CORS configuration
|
|
110
|
+
5. Audit logging for security events
|
|
111
|
+
|
|
112
|
+
For each:
|
|
113
|
+
- What to implement
|
|
114
|
+
- Where to add it
|
|
115
|
+
- Configuration recommendations
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
**Expected Output:**
|
|
119
|
+
- Security middleware
|
|
120
|
+
- Headers configuration
|
|
121
|
+
- Logging setup
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## Step 5: Verify Security Fixes
|
|
126
|
+
|
|
127
|
+
**Prompt:**
|
|
128
|
+
```
|
|
129
|
+
Verify the security fixes are effective:
|
|
130
|
+
|
|
131
|
+
For each fix made:
|
|
132
|
+
1. Attempt the original exploit - should fail
|
|
133
|
+
2. Check for bypass possibilities
|
|
134
|
+
3. Verify no regressions
|
|
135
|
+
4. Confirm logging works
|
|
136
|
+
|
|
137
|
+
Also:
|
|
138
|
+
- Run OWASP ZAP or similar scanner
|
|
139
|
+
- Review with security checklist
|
|
140
|
+
- Check for new issues introduced
|
|
141
|
+
|
|
142
|
+
Report findings.
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
**Expected Output:**
|
|
146
|
+
- Verification results
|
|
147
|
+
- Any remaining issues
|
|
148
|
+
- Scanner results
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## Step 6: Security Documentation
|
|
153
|
+
|
|
154
|
+
**Prompt:**
|
|
155
|
+
```
|
|
156
|
+
Document the security measures:
|
|
157
|
+
|
|
158
|
+
1. What security controls are in place?
|
|
159
|
+
2. How is authentication handled?
|
|
160
|
+
3. How is authorization handled?
|
|
161
|
+
4. What data is encrypted?
|
|
162
|
+
5. What is logged (and not logged)?
|
|
163
|
+
6. How to report security issues?
|
|
164
|
+
7. Incident response process?
|
|
165
|
+
|
|
166
|
+
Create a security section for documentation.
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
**Expected Output:**
|
|
170
|
+
- Security documentation
|
|
171
|
+
- Incident response plan
|
|
172
|
+
- Reporting process
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## Step 7: Ongoing Monitoring
|
|
177
|
+
|
|
178
|
+
**Prompt:**
|
|
179
|
+
```
|
|
180
|
+
Set up security monitoring:
|
|
181
|
+
|
|
182
|
+
1. What security events should trigger alerts?
|
|
183
|
+
2. What dashboards should exist?
|
|
184
|
+
3. How often should security scans run?
|
|
185
|
+
4. What's the process for security updates?
|
|
186
|
+
5. How to handle vulnerability disclosures?
|
|
187
|
+
|
|
188
|
+
Create a security operations plan.
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
**Expected Output:**
|
|
192
|
+
- Monitoring configuration
|
|
193
|
+
- Alert rules
|
|
194
|
+
- Operational procedures
|
|
195
|
+
|
|
196
|
+
---
|
|
197
|
+
|
|
198
|
+
## Chain Summary
|
|
199
|
+
|
|
200
|
+
| Step | Focus | Output |
|
|
201
|
+
|------|-------|--------|
|
|
202
|
+
| 1 | Audit | Issue inventory |
|
|
203
|
+
| 2 | Prioritize | Action plan |
|
|
204
|
+
| 3 | Fix | Patched vulnerabilities |
|
|
205
|
+
| 4 | Controls | Security infrastructure |
|
|
206
|
+
| 5 | Verify | Confirmed secure |
|
|
207
|
+
| 6 | Document | Security docs |
|
|
208
|
+
| 7 | Monitor | Ongoing vigilance |
|
|
209
|
+
|
|
210
|
+
## Security Checklist
|
|
211
|
+
|
|
212
|
+
### Authentication
|
|
213
|
+
- [ ] Passwords hashed with bcrypt/argon2
|
|
214
|
+
- [ ] Sessions expire appropriately
|
|
215
|
+
- [ ] MFA available for sensitive accounts
|
|
216
|
+
- [ ] Account lockout after failures
|
|
217
|
+
- [ ] Secure password reset flow
|
|
218
|
+
|
|
219
|
+
### Authorization
|
|
220
|
+
- [ ] Every endpoint checks permissions
|
|
221
|
+
- [ ] Role checks on sensitive operations
|
|
222
|
+
- [ ] No IDOR vulnerabilities
|
|
223
|
+
- [ ] Principle of least privilege
|
|
224
|
+
|
|
225
|
+
### Input/Output
|
|
226
|
+
- [ ] All input validated
|
|
227
|
+
- [ ] Output encoded/escaped
|
|
228
|
+
- [ ] File uploads validated
|
|
229
|
+
- [ ] No SQL injection possible
|
|
230
|
+
- [ ] No XSS possible
|
|
231
|
+
|
|
232
|
+
### Data Protection
|
|
233
|
+
- [ ] Sensitive data encrypted at rest
|
|
234
|
+
- [ ] TLS for data in transit
|
|
235
|
+
- [ ] No PII in logs
|
|
236
|
+
- [ ] Secure secret storage
|
|
237
|
+
|
|
238
|
+
### Infrastructure
|
|
239
|
+
- [ ] Security headers configured
|
|
240
|
+
- [ ] CORS properly restricted
|
|
241
|
+
- [ ] Rate limiting in place
|
|
242
|
+
- [ ] Debug mode disabled
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
# API Design Guide
|
|
2
|
+
|
|
3
|
+
> Best practices for designing REST APIs
|
|
4
|
+
|
|
5
|
+
## URL Structure
|
|
6
|
+
|
|
7
|
+
### Resource-Based URLs
|
|
8
|
+
```
|
|
9
|
+
GET /users # List users
|
|
10
|
+
GET /users/123 # Get user 123
|
|
11
|
+
POST /users # Create user
|
|
12
|
+
PUT /users/123 # Replace user 123
|
|
13
|
+
PATCH /users/123 # Update user 123
|
|
14
|
+
DELETE /users/123 # Delete user 123
|
|
15
|
+
|
|
16
|
+
# Nested resources
|
|
17
|
+
GET /users/123/posts # Posts by user 123
|
|
18
|
+
POST /users/123/posts # Create post for user 123
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### URL Guidelines
|
|
22
|
+
|
|
23
|
+
| Do | Don't |
|
|
24
|
+
|----|-------|
|
|
25
|
+
| `/users` | `/getUsers` |
|
|
26
|
+
| `/users/123` | `/user?id=123` |
|
|
27
|
+
| `/orders/456/items` | `/getOrderItems?orderId=456` |
|
|
28
|
+
| Use plural nouns | Use verbs in URLs |
|
|
29
|
+
| Use kebab-case | Use camelCase in URLs |
|
|
30
|
+
|
|
31
|
+
## HTTP Methods
|
|
32
|
+
|
|
33
|
+
| Method | Use | Idempotent | Body |
|
|
34
|
+
|--------|-----|------------|------|
|
|
35
|
+
| GET | Read | Yes | No |
|
|
36
|
+
| POST | Create | No | Yes |
|
|
37
|
+
| PUT | Replace | Yes | Yes |
|
|
38
|
+
| PATCH | Update | Yes | Yes |
|
|
39
|
+
| DELETE | Delete | Yes | No |
|
|
40
|
+
|
|
41
|
+
## Status Codes
|
|
42
|
+
|
|
43
|
+
### Success
|
|
44
|
+
- `200 OK` - General success
|
|
45
|
+
- `201 Created` - Resource created
|
|
46
|
+
- `204 No Content` - Success, no body (DELETE)
|
|
47
|
+
|
|
48
|
+
### Client Errors
|
|
49
|
+
- `400 Bad Request` - Invalid input
|
|
50
|
+
- `401 Unauthorized` - Not authenticated
|
|
51
|
+
- `403 Forbidden` - Not authorized
|
|
52
|
+
- `404 Not Found` - Resource doesn't exist
|
|
53
|
+
- `409 Conflict` - Duplicate, state conflict
|
|
54
|
+
- `422 Unprocessable Entity` - Validation failed
|
|
55
|
+
|
|
56
|
+
### Server Errors
|
|
57
|
+
- `500 Internal Server Error` - Server bug
|
|
58
|
+
- `503 Service Unavailable` - Temporary outage
|
|
59
|
+
|
|
60
|
+
## Request/Response Format
|
|
61
|
+
|
|
62
|
+
### Request Body
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"email": "user@example.com",
|
|
66
|
+
"name": "John Doe"
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Success Response
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"data": {
|
|
74
|
+
"id": "123",
|
|
75
|
+
"email": "user@example.com",
|
|
76
|
+
"name": "John Doe",
|
|
77
|
+
"createdAt": "2024-01-15T10:00:00Z"
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
### Error Response
|
|
83
|
+
```json
|
|
84
|
+
{
|
|
85
|
+
"error": {
|
|
86
|
+
"code": "VALIDATION_ERROR",
|
|
87
|
+
"message": "Invalid input",
|
|
88
|
+
"details": [
|
|
89
|
+
{ "field": "email", "message": "Invalid format" }
|
|
90
|
+
]
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Collection Response
|
|
96
|
+
```json
|
|
97
|
+
{
|
|
98
|
+
"data": [
|
|
99
|
+
{ "id": "1", "name": "Item 1" },
|
|
100
|
+
{ "id": "2", "name": "Item 2" }
|
|
101
|
+
],
|
|
102
|
+
"meta": {
|
|
103
|
+
"page": 1,
|
|
104
|
+
"perPage": 20,
|
|
105
|
+
"total": 45,
|
|
106
|
+
"totalPages": 3
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Pagination
|
|
112
|
+
|
|
113
|
+
### Query Parameters
|
|
114
|
+
```
|
|
115
|
+
GET /users?page=2&per_page=20
|
|
116
|
+
GET /users?offset=20&limit=20
|
|
117
|
+
GET /users?cursor=abc123
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Response Headers
|
|
121
|
+
```
|
|
122
|
+
Link: <https://api.example.com/users?page=3>; rel="next",
|
|
123
|
+
<https://api.example.com/users?page=1>; rel="prev"
|
|
124
|
+
X-Total-Count: 100
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Filtering & Sorting
|
|
128
|
+
|
|
129
|
+
```
|
|
130
|
+
# Filtering
|
|
131
|
+
GET /products?category=electronics&min_price=100
|
|
132
|
+
|
|
133
|
+
# Sorting
|
|
134
|
+
GET /products?sort=price
|
|
135
|
+
GET /products?sort=-createdAt # Descending
|
|
136
|
+
GET /products?sort=category,price
|
|
137
|
+
|
|
138
|
+
# Searching
|
|
139
|
+
GET /products?search=laptop
|
|
140
|
+
GET /products?q=laptop
|
|
141
|
+
|
|
142
|
+
# Field selection
|
|
143
|
+
GET /users?fields=id,name,email
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Versioning
|
|
147
|
+
|
|
148
|
+
### URL Versioning (Recommended)
|
|
149
|
+
```
|
|
150
|
+
/api/v1/users
|
|
151
|
+
/api/v2/users
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
### Header Versioning
|
|
155
|
+
```
|
|
156
|
+
Accept: application/vnd.api+json;version=1
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Authentication
|
|
160
|
+
|
|
161
|
+
### Bearer Token
|
|
162
|
+
```
|
|
163
|
+
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### API Key
|
|
167
|
+
```
|
|
168
|
+
X-API-Key: your-api-key
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Rate Limiting
|
|
172
|
+
|
|
173
|
+
### Headers
|
|
174
|
+
```
|
|
175
|
+
X-RateLimit-Limit: 100
|
|
176
|
+
X-RateLimit-Remaining: 95
|
|
177
|
+
X-RateLimit-Reset: 1640000000
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### Response (429 Too Many Requests)
|
|
181
|
+
```json
|
|
182
|
+
{
|
|
183
|
+
"error": {
|
|
184
|
+
"code": "RATE_LIMIT_EXCEEDED",
|
|
185
|
+
"message": "Too many requests",
|
|
186
|
+
"retryAfter": 60
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
## Common Patterns
|
|
192
|
+
|
|
193
|
+
### Partial Updates (PATCH)
|
|
194
|
+
```json
|
|
195
|
+
// Only update provided fields
|
|
196
|
+
PATCH /users/123
|
|
197
|
+
{
|
|
198
|
+
"name": "New Name"
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### Bulk Operations
|
|
203
|
+
```
|
|
204
|
+
POST /users/bulk
|
|
205
|
+
{
|
|
206
|
+
"operations": [
|
|
207
|
+
{ "action": "create", "data": {...} },
|
|
208
|
+
{ "action": "update", "id": "123", "data": {...} }
|
|
209
|
+
]
|
|
210
|
+
}
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
### Async Operations
|
|
214
|
+
```
|
|
215
|
+
POST /reports
|
|
216
|
+
→ 202 Accepted
|
|
217
|
+
{
|
|
218
|
+
"id": "job-123",
|
|
219
|
+
"status": "processing",
|
|
220
|
+
"statusUrl": "/jobs/job-123"
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
GET /jobs/job-123
|
|
224
|
+
→ 200 OK
|
|
225
|
+
{
|
|
226
|
+
"status": "completed",
|
|
227
|
+
"result": {...}
|
|
228
|
+
}
|
|
229
|
+
```
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# Error Handling Guide
|
|
2
|
+
|
|
3
|
+
> Best practices for handling errors across the stack
|
|
4
|
+
|
|
5
|
+
## Principles
|
|
6
|
+
|
|
7
|
+
1. **Fail fast**: Validate early, throw early
|
|
8
|
+
2. **Be specific**: Custom errors over generic ones
|
|
9
|
+
3. **Don't hide**: Log everything, show appropriate messages
|
|
10
|
+
4. **Recover gracefully**: Degrade instead of crash
|
|
11
|
+
|
|
12
|
+
## Error Types
|
|
13
|
+
|
|
14
|
+
### Operational Errors (Expected)
|
|
15
|
+
- Invalid user input
|
|
16
|
+
- Resource not found
|
|
17
|
+
- Permission denied
|
|
18
|
+
- External service failure
|
|
19
|
+
|
|
20
|
+
**Handling**: Catch, handle gracefully, inform user
|
|
21
|
+
|
|
22
|
+
### Programmer Errors (Bugs)
|
|
23
|
+
- Type errors
|
|
24
|
+
- Null pointer exceptions
|
|
25
|
+
- Assertion failures
|
|
26
|
+
|
|
27
|
+
**Handling**: Crash, fix the bug, deploy
|
|
28
|
+
|
|
29
|
+
## Custom Error Classes
|
|
30
|
+
|
|
31
|
+
### TypeScript
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
// Base error
|
|
35
|
+
class AppError extends Error {
|
|
36
|
+
constructor(
|
|
37
|
+
message: string,
|
|
38
|
+
public statusCode: number = 500,
|
|
39
|
+
public code: string = 'INTERNAL_ERROR',
|
|
40
|
+
public isOperational: boolean = true
|
|
41
|
+
) {
|
|
42
|
+
super(message);
|
|
43
|
+
this.name = 'AppError';
|
|
44
|
+
Error.captureStackTrace(this, this.constructor);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Specific errors
|
|
49
|
+
class NotFoundError extends AppError {
|
|
50
|
+
constructor(resource: string) {
|
|
51
|
+
super(`${resource} not found`, 404, 'NOT_FOUND');
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
class ValidationError extends AppError {
|
|
56
|
+
constructor(message: string, public details?: object) {
|
|
57
|
+
super(message, 400, 'VALIDATION_ERROR');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
class UnauthorizedError extends AppError {
|
|
62
|
+
constructor(message = 'Unauthorized') {
|
|
63
|
+
super(message, 401, 'UNAUTHORIZED');
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
class ForbiddenError extends AppError {
|
|
68
|
+
constructor(message = 'Forbidden') {
|
|
69
|
+
super(message, 403, 'FORBIDDEN');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
class ConflictError extends AppError {
|
|
74
|
+
constructor(message: string) {
|
|
75
|
+
super(message, 409, 'CONFLICT');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
### Python
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
class AppError(Exception):
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
message: str,
|
|
87
|
+
status_code: int = 500,
|
|
88
|
+
code: str = "INTERNAL_ERROR"
|
|
89
|
+
):
|
|
90
|
+
self.message = message
|
|
91
|
+
self.status_code = status_code
|
|
92
|
+
self.code = code
|
|
93
|
+
super().__init__(message)
|
|
94
|
+
|
|
95
|
+
class NotFoundError(AppError):
|
|
96
|
+
def __init__(self, resource: str):
|
|
97
|
+
super().__init__(f"{resource} not found", 404, "NOT_FOUND")
|
|
98
|
+
|
|
99
|
+
class ValidationError(AppError):
|
|
100
|
+
def __init__(self, message: str, details: dict = None):
|
|
101
|
+
super().__init__(message, 400, "VALIDATION_ERROR")
|
|
102
|
+
self.details = details
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Error Handling Patterns
|
|
106
|
+
|
|
107
|
+
### Express Middleware
|
|
108
|
+
|
|
109
|
+
```typescript
|
|
110
|
+
// Global error handler
|
|
111
|
+
function errorHandler(
|
|
112
|
+
err: Error,
|
|
113
|
+
req: Request,
|
|
114
|
+
res: Response,
|
|
115
|
+
next: NextFunction
|
|
116
|
+
) {
|
|
117
|
+
// Log error
|
|
118
|
+
logger.error({
|
|
119
|
+
message: err.message,
|
|
120
|
+
stack: err.stack,
|
|
121
|
+
path: req.path,
|
|
122
|
+
method: req.method,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
// Operational error - send to client
|
|
126
|
+
if (err instanceof AppError && err.isOperational) {
|
|
127
|
+
return res.status(err.statusCode).json({
|
|
128
|
+
error: {
|
|
129
|
+
code: err.code,
|
|
130
|
+
message: err.message,
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Programmer error - generic message
|
|
136
|
+
res.status(500).json({
|
|
137
|
+
error: {
|
|
138
|
+
code: 'INTERNAL_ERROR',
|
|
139
|
+
message: 'Something went wrong',
|
|
140
|
+
},
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Async Handler Wrapper
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
function asyncHandler(fn: RequestHandler): RequestHandler {
|
|
149
|
+
return (req, res, next) => {
|
|
150
|
+
Promise.resolve(fn(req, res, next)).catch(next);
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Usage
|
|
155
|
+
router.get('/users/:id', asyncHandler(async (req, res) => {
|
|
156
|
+
const user = await userService.getById(req.params.id);
|
|
157
|
+
if (!user) throw new NotFoundError('User');
|
|
158
|
+
res.json(user);
|
|
159
|
+
}));
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### FastAPI
|
|
163
|
+
|
|
164
|
+
```python
|
|
165
|
+
from fastapi import FastAPI, Request
|
|
166
|
+
from fastapi.responses import JSONResponse
|
|
167
|
+
|
|
168
|
+
app = FastAPI()
|
|
169
|
+
|
|
170
|
+
@app.exception_handler(AppError)
|
|
171
|
+
async def app_error_handler(request: Request, exc: AppError):
|
|
172
|
+
return JSONResponse(
|
|
173
|
+
status_code=exc.status_code,
|
|
174
|
+
content={"error": {"code": exc.code, "message": exc.message}}
|
|
175
|
+
)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Client-Facing Errors
|
|
179
|
+
|
|
180
|
+
### Response Format
|
|
181
|
+
|
|
182
|
+
```json
|
|
183
|
+
{
|
|
184
|
+
"error": {
|
|
185
|
+
"code": "VALIDATION_ERROR",
|
|
186
|
+
"message": "Invalid input",
|
|
187
|
+
"details": [
|
|
188
|
+
{ "field": "email", "message": "Invalid email format" },
|
|
189
|
+
{ "field": "password", "message": "Must be at least 8 characters" }
|
|
190
|
+
]
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
### Never Expose
|
|
196
|
+
|
|
197
|
+
- Stack traces
|
|
198
|
+
- Database errors
|
|
199
|
+
- Internal paths
|
|
200
|
+
- Implementation details
|
|
201
|
+
|
|
202
|
+
## Logging Errors
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
// Good error log
|
|
206
|
+
logger.error('Failed to process payment', {
|
|
207
|
+
error: err.message,
|
|
208
|
+
stack: err.stack,
|
|
209
|
+
userId: user.id,
|
|
210
|
+
orderId: order.id,
|
|
211
|
+
paymentMethod: method.type,
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// Bad - logs sensitive data
|
|
215
|
+
logger.error('Payment failed', {
|
|
216
|
+
cardNumber: card.number, // Don't log!
|
|
217
|
+
error: err
|
|
218
|
+
});
|
|
219
|
+
```
|