@zimezone/z-command 1.1.1 → 1.1.2

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.
Files changed (282) hide show
  1. package/README.md +13 -1
  2. package/dist/commands/init.d.ts.map +1 -1
  3. package/dist/commands/init.js +34 -9
  4. package/dist/commands/init.js.map +1 -1
  5. package/package.json +8 -3
  6. package/templates.zip +0 -0
  7. package/templates/agents/accessibility-expert.agent.md +0 -56
  8. package/templates/agents/ai-engineer.agent.md +0 -61
  9. package/templates/agents/angular-architect.agent.md +0 -49
  10. package/templates/agents/api-designer.agent.md +0 -40
  11. package/templates/agents/api-documenter.agent.md +0 -161
  12. package/templates/agents/architect-review.agent.md +0 -146
  13. package/templates/agents/arm-cortex-expert.agent.md +0 -288
  14. package/templates/agents/azure-infra-engineer.agent.md +0 -57
  15. package/templates/agents/backend-architect.agent.md +0 -309
  16. package/templates/agents/backend-developer.agent.md +0 -61
  17. package/templates/agents/backend-security-coder.agent.md +0 -152
  18. package/templates/agents/bash-pro.agent.md +0 -285
  19. package/templates/agents/blockchain-developer.agent.md +0 -57
  20. package/templates/agents/build-engineer.agent.md +0 -56
  21. package/templates/agents/business-analyst.agent.md +0 -47
  22. package/templates/agents/c-pro.agent.md +0 -35
  23. package/templates/agents/c4-code.agent.md +0 -320
  24. package/templates/agents/c4-component.agent.md +0 -227
  25. package/templates/agents/c4-container.agent.md +0 -248
  26. package/templates/agents/c4-context.agent.md +0 -235
  27. package/templates/agents/cli-developer.agent.md +0 -57
  28. package/templates/agents/cloud-architect.agent.md +0 -56
  29. package/templates/agents/code-architect.agent.md +0 -63
  30. package/templates/agents/code-reviewer.agent.md +0 -49
  31. package/templates/agents/competitive-analyst.agent.md +0 -48
  32. package/templates/agents/conductor-validator.agent.md +0 -245
  33. package/templates/agents/context-manager.agent.md +0 -55
  34. package/templates/agents/cpp-pro.agent.md +0 -59
  35. package/templates/agents/csharp-developer.agent.md +0 -57
  36. package/templates/agents/csharp-pro.agent.md +0 -38
  37. package/templates/agents/customer-support.agent.md +0 -148
  38. package/templates/agents/data-engineer.agent.md +0 -55
  39. package/templates/agents/data-researcher.agent.md +0 -55
  40. package/templates/agents/data-scientist.agent.md +0 -56
  41. package/templates/agents/database-admin.agent.md +0 -142
  42. package/templates/agents/database-administrator.agent.md +0 -50
  43. package/templates/agents/database-architect.agent.md +0 -238
  44. package/templates/agents/database-optimizer.agent.md +0 -144
  45. package/templates/agents/debugger.agent.md +0 -30
  46. package/templates/agents/deployment-engineer.agent.md +0 -0
  47. package/templates/agents/devops-engineer.agent.md +0 -59
  48. package/templates/agents/devops-troubleshooter.agent.md +0 -138
  49. package/templates/agents/django-developer.agent.md +0 -50
  50. package/templates/agents/django-pro.agent.md +0 -159
  51. package/templates/agents/docs-architect.agent.md +0 -77
  52. package/templates/agents/documentation-engineer.agent.md +0 -57
  53. package/templates/agents/dotnet-architect.agent.md +0 -175
  54. package/templates/agents/dx-optimizer.agent.md +0 -63
  55. package/templates/agents/electron-pro.agent.md +0 -56
  56. package/templates/agents/elixir-pro.agent.md +0 -38
  57. package/templates/agents/embedded-systems.agent.md +0 -55
  58. package/templates/agents/error-detective.agent.md +0 -32
  59. package/templates/agents/event-sourcing-architect.agent.md +0 -42
  60. package/templates/agents/fastapi-pro.agent.md +0 -171
  61. package/templates/agents/fintech-engineer.agent.md +0 -57
  62. package/templates/agents/firmware-analyst.agent.md +0 -330
  63. package/templates/agents/flutter-expert.agent.md +0 -50
  64. package/templates/agents/frontend-developer.agent.md +0 -59
  65. package/templates/agents/frontend-security-coder.agent.md +0 -149
  66. package/templates/agents/fullstack-developer.agent.md +0 -46
  67. package/templates/agents/git-workflow-manager.agent.md +0 -57
  68. package/templates/agents/golang-pro.agent.md +0 -50
  69. package/templates/agents/graphql-architect.agent.md +0 -48
  70. package/templates/agents/haskell-pro.agent.md +0 -37
  71. package/templates/agents/hr-pro.agent.md +0 -105
  72. package/templates/agents/incident-responder.agent.md +0 -190
  73. package/templates/agents/ios-developer.agent.md +0 -198
  74. package/templates/agents/iot-engineer.agent.md +0 -56
  75. package/templates/agents/java-architect.agent.md +0 -48
  76. package/templates/agents/java-pro.agent.md +0 -156
  77. package/templates/agents/javascript-pro.agent.md +0 -35
  78. package/templates/agents/julia-pro.agent.md +0 -187
  79. package/templates/agents/kotlin-specialist.agent.md +0 -50
  80. package/templates/agents/laravel-specialist.agent.md +0 -50
  81. package/templates/agents/legacy-modernizer.agent.md +0 -56
  82. package/templates/agents/legal-advisor.agent.md +0 -49
  83. package/templates/agents/llm-architect.agent.md +0 -58
  84. package/templates/agents/malware-analyst.agent.md +0 -272
  85. package/templates/agents/mcp-developer.agent.md +0 -54
  86. package/templates/agents/mermaid-expert.agent.md +0 -39
  87. package/templates/agents/microservices-architect.agent.md +0 -47
  88. package/templates/agents/minecraft-bukkit-pro.agent.md +0 -104
  89. package/templates/agents/ml-engineer.agent.md +0 -56
  90. package/templates/agents/mlops-engineer.agent.md +0 -56
  91. package/templates/agents/mobile-developer.agent.md +0 -45
  92. package/templates/agents/mobile-security-coder.agent.md +0 -163
  93. package/templates/agents/monorepo-architect.agent.md +0 -44
  94. package/templates/agents/multi-agent-coordinator.agent.md +0 -55
  95. package/templates/agents/network-engineer.agent.md +0 -57
  96. package/templates/agents/nextjs-developer.agent.md +0 -48
  97. package/templates/agents/nlp-engineer.agent.md +0 -58
  98. package/templates/agents/observability-engineer.agent.md +0 -228
  99. package/templates/agents/payment-integration.agent.md +0 -56
  100. package/templates/agents/performance-engineer.agent.md +0 -167
  101. package/templates/agents/performance-optimizer.agent.md +0 -57
  102. package/templates/agents/php-pro.agent.md +0 -43
  103. package/templates/agents/platform-engineer.agent.md +0 -57
  104. package/templates/agents/posix-shell-pro.agent.md +0 -284
  105. package/templates/agents/postgres-pro.agent.md +0 -58
  106. package/templates/agents/product-manager.agent.md +0 -55
  107. package/templates/agents/project-manager.agent.md +0 -57
  108. package/templates/agents/prompt-engineer.agent.md +0 -58
  109. package/templates/agents/python-pro.agent.md +0 -48
  110. package/templates/agents/quant-analyst.agent.md +0 -32
  111. package/templates/agents/rails-expert.agent.md +0 -50
  112. package/templates/agents/react-specialist.agent.md +0 -49
  113. package/templates/agents/refactoring-specialist.agent.md +0 -56
  114. package/templates/agents/reference-builder.agent.md +0 -167
  115. package/templates/agents/research-analyst.agent.md +0 -63
  116. package/templates/agents/reverse-engineer.agent.md +0 -202
  117. package/templates/agents/risk-manager.agent.md +0 -41
  118. package/templates/agents/ruby-pro.agent.md +0 -35
  119. package/templates/agents/rust-pro.agent.md +0 -156
  120. package/templates/agents/sales-automator.agent.md +0 -35
  121. package/templates/agents/scala-pro.agent.md +0 -60
  122. package/templates/agents/scrum-master.agent.md +0 -54
  123. package/templates/agents/search-specialist.agent.md +0 -59
  124. package/templates/agents/security-analyst.agent.md +0 -57
  125. package/templates/agents/security-auditor.agent.md +0 -138
  126. package/templates/agents/security-engineer.agent.md +0 -57
  127. package/templates/agents/seo-authority-builder.agent.md +0 -116
  128. package/templates/agents/seo-cannibalization-detector.agent.md +0 -103
  129. package/templates/agents/seo-content-auditor.agent.md +0 -63
  130. package/templates/agents/seo-content-planner.agent.md +0 -88
  131. package/templates/agents/seo-content-refresher.agent.md +0 -98
  132. package/templates/agents/seo-content-writer.agent.md +0 -76
  133. package/templates/agents/seo-keyword-strategist.agent.md +0 -75
  134. package/templates/agents/seo-meta-optimizer.agent.md +0 -72
  135. package/templates/agents/seo-snippet-hunter.agent.md +0 -94
  136. package/templates/agents/seo-specialist.agent.md +0 -57
  137. package/templates/agents/seo-structure-architect.agent.md +0 -88
  138. package/templates/agents/service-mesh-expert.agent.md +0 -41
  139. package/templates/agents/sql-pro.agent.md +0 -146
  140. package/templates/agents/sre-engineer.agent.md +0 -58
  141. package/templates/agents/swift-expert.agent.md +0 -49
  142. package/templates/agents/task-distributor.agent.md +0 -47
  143. package/templates/agents/tdd-orchestrator.agent.md +0 -183
  144. package/templates/agents/technical-writer.agent.md +0 -48
  145. package/templates/agents/temporal-python-pro.agent.md +0 -349
  146. package/templates/agents/terraform-engineer.agent.md +0 -57
  147. package/templates/agents/terraform-specialist.agent.md +0 -137
  148. package/templates/agents/test-automator.agent.md +0 -203
  149. package/templates/agents/test-engineer.agent.md +0 -55
  150. package/templates/agents/threat-modeling-expert.agent.md +0 -44
  151. package/templates/agents/trend-analyst.agent.md +0 -47
  152. package/templates/agents/tutorial-engineer.agent.md +0 -118
  153. package/templates/agents/typescript-pro.agent.md +0 -48
  154. package/templates/agents/ui-designer.agent.md +0 -48
  155. package/templates/agents/ui-ux-designer.agent.md +0 -188
  156. package/templates/agents/ui-visual-validator.agent.md +0 -192
  157. package/templates/agents/ux-researcher.agent.md +0 -48
  158. package/templates/agents/vector-database-engineer.agent.md +0 -43
  159. package/templates/agents/vue-expert.agent.md +0 -48
  160. package/templates/agents/websocket-engineer.agent.md +0 -49
  161. package/templates/agents/workflow-orchestrator.agent.md +0 -48
  162. package/templates/skills/angular-migration/SKILL.md +0 -410
  163. package/templates/skills/api-design-principles/SKILL.md +0 -528
  164. package/templates/skills/api-design-principles/assets/api-design-checklist.md +0 -155
  165. package/templates/skills/api-design-principles/assets/rest-api-template.py +0 -182
  166. package/templates/skills/api-design-principles/references/graphql-schema-design.md +0 -583
  167. package/templates/skills/api-design-principles/references/rest-best-practices.md +0 -408
  168. package/templates/skills/architecture-decision-records/SKILL.md +0 -428
  169. package/templates/skills/architecture-patterns/SKILL.md +0 -494
  170. package/templates/skills/async-python-patterns/SKILL.md +0 -694
  171. package/templates/skills/auth-implementation-patterns/SKILL.md +0 -634
  172. package/templates/skills/changelog-automation/SKILL.md +0 -552
  173. package/templates/skills/code-review/SKILL.md +0 -62
  174. package/templates/skills/code-review-excellence/SKILL.md +0 -520
  175. package/templates/skills/competitive-landscape/SKILL.md +0 -479
  176. package/templates/skills/context-driven-development/SKILL.md +0 -385
  177. package/templates/skills/cost-optimization/SKILL.md +0 -274
  178. package/templates/skills/cqrs-implementation/SKILL.md +0 -554
  179. package/templates/skills/data-quality-frameworks/SKILL.md +0 -587
  180. package/templates/skills/data-storytelling/SKILL.md +0 -453
  181. package/templates/skills/database-migration/SKILL.md +0 -424
  182. package/templates/skills/dbt-transformation-patterns/SKILL.md +0 -561
  183. package/templates/skills/debugging-strategies/SKILL.md +0 -527
  184. package/templates/skills/defi-protocol-templates/SKILL.md +0 -454
  185. package/templates/skills/dependency-upgrade/SKILL.md +0 -409
  186. package/templates/skills/deployment-pipeline-design/SKILL.md +0 -359
  187. package/templates/skills/distributed-tracing/SKILL.md +0 -438
  188. package/templates/skills/dotnet-backend-patterns/SKILL.md +0 -815
  189. package/templates/skills/dotnet-backend-patterns/assets/repository-template.cs +0 -523
  190. package/templates/skills/dotnet-backend-patterns/assets/service-template.cs +0 -336
  191. package/templates/skills/dotnet-backend-patterns/references/dapper-patterns.md +0 -544
  192. package/templates/skills/dotnet-backend-patterns/references/ef-core-best-practices.md +0 -355
  193. package/templates/skills/e2e-testing-patterns/SKILL.md +0 -547
  194. package/templates/skills/employment-contract-templates/SKILL.md +0 -507
  195. package/templates/skills/error-handling-patterns/SKILL.md +0 -636
  196. package/templates/skills/event-store-design/SKILL.md +0 -437
  197. package/templates/skills/fastapi-templates/SKILL.md +0 -567
  198. package/templates/skills/git-advanced-workflows/SKILL.md +0 -400
  199. package/templates/skills/github-actions-templates/SKILL.md +0 -333
  200. package/templates/skills/go-concurrency-patterns/SKILL.md +0 -655
  201. package/templates/skills/grafana-dashboards/SKILL.md +0 -369
  202. package/templates/skills/helm-chart-scaffolding/SKILL.md +0 -544
  203. package/templates/skills/helm-chart-scaffolding/assets/Chart.yaml.template +0 -42
  204. package/templates/skills/helm-chart-scaffolding/assets/values.yaml.template +0 -185
  205. package/templates/skills/helm-chart-scaffolding/references/chart-structure.md +0 -500
  206. package/templates/skills/helm-chart-scaffolding/scripts/validate-chart.sh +0 -244
  207. package/templates/skills/javascript-testing-patterns/SKILL.md +0 -1025
  208. package/templates/skills/langchain-architecture/SKILL.md +0 -338
  209. package/templates/skills/llm-evaluation/SKILL.md +0 -471
  210. package/templates/skills/microservices-patterns/SKILL.md +0 -595
  211. package/templates/skills/modern-javascript-patterns/SKILL.md +0 -911
  212. package/templates/skills/monorepo-management/SKILL.md +0 -622
  213. package/templates/skills/nextjs-app-router-patterns/SKILL.md +0 -544
  214. package/templates/skills/nodejs-backend-patterns/SKILL.md +0 -1020
  215. package/templates/skills/nx-workspace-patterns/SKILL.md +0 -452
  216. package/templates/skills/openapi-spec-generation/SKILL.md +0 -1028
  217. package/templates/skills/paypal-integration/SKILL.md +0 -467
  218. package/templates/skills/pci-compliance/SKILL.md +0 -466
  219. package/templates/skills/postgresql/SKILL.md +0 -204
  220. package/templates/skills/projection-patterns/SKILL.md +0 -490
  221. package/templates/skills/prometheus-configuration/SKILL.md +0 -392
  222. package/templates/skills/prompt-engineering-patterns/SKILL.md +0 -201
  223. package/templates/skills/prompt-engineering-patterns/assets/few-shot-examples.json +0 -106
  224. package/templates/skills/prompt-engineering-patterns/assets/prompt-template-library.md +0 -246
  225. package/templates/skills/prompt-engineering-patterns/references/chain-of-thought.md +0 -399
  226. package/templates/skills/prompt-engineering-patterns/references/few-shot-learning.md +0 -369
  227. package/templates/skills/prompt-engineering-patterns/references/prompt-optimization.md +0 -414
  228. package/templates/skills/prompt-engineering-patterns/references/prompt-templates.md +0 -470
  229. package/templates/skills/prompt-engineering-patterns/references/system-prompts.md +0 -189
  230. package/templates/skills/prompt-engineering-patterns/scripts/optimize-prompt.py +0 -279
  231. package/templates/skills/python-packaging/SKILL.md +0 -870
  232. package/templates/skills/python-performance-optimization/SKILL.md +0 -869
  233. package/templates/skills/python-testing-patterns/SKILL.md +0 -907
  234. package/templates/skills/rag-implementation/SKILL.md +0 -403
  235. package/templates/skills/react-modernization/SKILL.md +0 -513
  236. package/templates/skills/react-native-architecture/SKILL.md +0 -671
  237. package/templates/skills/react-state-management/SKILL.md +0 -429
  238. package/templates/skills/risk-metrics-calculation/SKILL.md +0 -555
  239. package/templates/skills/rust-async-patterns/SKILL.md +0 -517
  240. package/templates/skills/secrets-management/SKILL.md +0 -346
  241. package/templates/skills/security-requirement-extraction/SKILL.md +0 -677
  242. package/templates/skills/security-review/SKILL.md +0 -78
  243. package/templates/skills/shellcheck-configuration/SKILL.md +0 -454
  244. package/templates/skills/similarity-search-patterns/SKILL.md +0 -558
  245. package/templates/skills/slo-implementation/SKILL.md +0 -329
  246. package/templates/skills/sql-optimization-patterns/SKILL.md +0 -493
  247. package/templates/skills/stripe-integration/SKILL.md +0 -442
  248. package/templates/skills/systematic-debugging/SKILL.md +0 -57
  249. package/templates/skills/tailwind-design-system/SKILL.md +0 -666
  250. package/templates/skills/temporal-python-testing/SKILL.md +0 -158
  251. package/templates/skills/temporal-python-testing/resources/integration-testing.md +0 -455
  252. package/templates/skills/temporal-python-testing/resources/local-setup.md +0 -553
  253. package/templates/skills/temporal-python-testing/resources/replay-testing.md +0 -462
  254. package/templates/skills/temporal-python-testing/resources/unit-testing.md +0 -328
  255. package/templates/skills/terraform-module-library/SKILL.md +0 -249
  256. package/templates/skills/terraform-module-library/references/aws-modules.md +0 -63
  257. package/templates/skills/test-driven-development/SKILL.md +0 -46
  258. package/templates/skills/threat-mitigation-mapping/SKILL.md +0 -745
  259. package/templates/skills/track-management/SKILL.md +0 -593
  260. package/templates/skills/typescript-advanced-types/SKILL.md +0 -717
  261. package/templates/skills/ui-ux-pro-max/SKILL.md +0 -352
  262. package/templates/skills/ui-ux-pro-max/data/charts.csv +0 -26
  263. package/templates/skills/ui-ux-pro-max/data/colors.csv +0 -97
  264. package/templates/skills/ui-ux-pro-max/data/icons.csv +0 -101
  265. package/templates/skills/ui-ux-pro-max/data/landing.csv +0 -31
  266. package/templates/skills/ui-ux-pro-max/data/products.csv +0 -97
  267. package/templates/skills/ui-ux-pro-max/data/prompts.csv +0 -24
  268. package/templates/skills/ui-ux-pro-max/data/react-performance.csv +0 -45
  269. package/templates/skills/ui-ux-pro-max/data/styles.csv +0 -59
  270. package/templates/skills/ui-ux-pro-max/data/typography.csv +0 -58
  271. package/templates/skills/ui-ux-pro-max/data/ui-reasoning.csv +0 -101
  272. package/templates/skills/ui-ux-pro-max/data/ux-guidelines.csv +0 -100
  273. package/templates/skills/ui-ux-pro-max/data/web-interface.csv +0 -31
  274. package/templates/skills/ui-ux-pro-max/scripts/core.py +0 -258
  275. package/templates/skills/ui-ux-pro-max/scripts/design_system.py +0 -547
  276. package/templates/skills/ui-ux-pro-max/scripts/search.py +0 -76
  277. package/templates/skills/uv-package-manager/SKILL.md +0 -831
  278. package/templates/skills/vector-index-tuning/SKILL.md +0 -521
  279. package/templates/skills/wcag-audit-patterns/SKILL.md +0 -555
  280. package/templates/skills/workflow-orchestration-patterns/SKILL.md +0 -316
  281. package/templates/skills/workflow-patterns/SKILL.md +0 -623
  282. package/templates/skills/writing-plans/SKILL.md +0 -64
@@ -1,636 +0,0 @@
1
- ---
2
- name: error-handling-patterns
3
- description: Master error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.
4
- ---
5
-
6
- # Error Handling Patterns
7
-
8
- Build resilient applications with robust error handling strategies that gracefully handle failures and provide excellent debugging experiences.
9
-
10
- ## When to Use This Skill
11
-
12
- - Implementing error handling in new features
13
- - Designing error-resilient APIs
14
- - Debugging production issues
15
- - Improving application reliability
16
- - Creating better error messages for users and developers
17
- - Implementing retry and circuit breaker patterns
18
- - Handling async/concurrent errors
19
- - Building fault-tolerant distributed systems
20
-
21
- ## Core Concepts
22
-
23
- ### 1. Error Handling Philosophies
24
-
25
- **Exceptions vs Result Types:**
26
- - **Exceptions**: Traditional try-catch, disrupts control flow
27
- - **Result Types**: Explicit success/failure, functional approach
28
- - **Error Codes**: C-style, requires discipline
29
- - **Option/Maybe Types**: For nullable values
30
-
31
- **When to Use Each:**
32
- - Exceptions: Unexpected errors, exceptional conditions
33
- - Result Types: Expected errors, validation failures
34
- - Panics/Crashes: Unrecoverable errors, programming bugs
35
-
36
- ### 2. Error Categories
37
-
38
- **Recoverable Errors:**
39
- - Network timeouts
40
- - Missing files
41
- - Invalid user input
42
- - API rate limits
43
-
44
- **Unrecoverable Errors:**
45
- - Out of memory
46
- - Stack overflow
47
- - Programming bugs (null pointer, etc.)
48
-
49
- ## Language-Specific Patterns
50
-
51
- ### Python Error Handling
52
-
53
- **Custom Exception Hierarchy:**
54
- ```python
55
- class ApplicationError(Exception):
56
- """Base exception for all application errors."""
57
- def __init__(self, message: str, code: str = None, details: dict = None):
58
- super().__init__(message)
59
- self.code = code
60
- self.details = details or {}
61
- self.timestamp = datetime.utcnow()
62
-
63
- class ValidationError(ApplicationError):
64
- """Raised when validation fails."""
65
- pass
66
-
67
- class NotFoundError(ApplicationError):
68
- """Raised when resource not found."""
69
- pass
70
-
71
- class ExternalServiceError(ApplicationError):
72
- """Raised when external service fails."""
73
- def __init__(self, message: str, service: str, **kwargs):
74
- super().__init__(message, **kwargs)
75
- self.service = service
76
-
77
- # Usage
78
- def get_user(user_id: str) -> User:
79
- user = db.query(User).filter_by(id=user_id).first()
80
- if not user:
81
- raise NotFoundError(
82
- f"User not found",
83
- code="USER_NOT_FOUND",
84
- details={"user_id": user_id}
85
- )
86
- return user
87
- ```
88
-
89
- **Context Managers for Cleanup:**
90
- ```python
91
- from contextlib import contextmanager
92
-
93
- @contextmanager
94
- def database_transaction(session):
95
- """Ensure transaction is committed or rolled back."""
96
- try:
97
- yield session
98
- session.commit()
99
- except Exception as e:
100
- session.rollback()
101
- raise
102
- finally:
103
- session.close()
104
-
105
- # Usage
106
- with database_transaction(db.session) as session:
107
- user = User(name="Alice")
108
- session.add(user)
109
- # Automatic commit or rollback
110
- ```
111
-
112
- **Retry with Exponential Backoff:**
113
- ```python
114
- import time
115
- from functools import wraps
116
- from typing import TypeVar, Callable
117
-
118
- T = TypeVar('T')
119
-
120
- def retry(
121
- max_attempts: int = 3,
122
- backoff_factor: float = 2.0,
123
- exceptions: tuple = (Exception,)
124
- ):
125
- """Retry decorator with exponential backoff."""
126
- def decorator(func: Callable[..., T]) -> Callable[..., T]:
127
- @wraps(func)
128
- def wrapper(*args, **kwargs) -> T:
129
- last_exception = None
130
- for attempt in range(max_attempts):
131
- try:
132
- return func(*args, **kwargs)
133
- except exceptions as e:
134
- last_exception = e
135
- if attempt < max_attempts - 1:
136
- sleep_time = backoff_factor ** attempt
137
- time.sleep(sleep_time)
138
- continue
139
- raise
140
- raise last_exception
141
- return wrapper
142
- return decorator
143
-
144
- # Usage
145
- @retry(max_attempts=3, exceptions=(NetworkError,))
146
- def fetch_data(url: str) -> dict:
147
- response = requests.get(url, timeout=5)
148
- response.raise_for_status()
149
- return response.json()
150
- ```
151
-
152
- ### TypeScript/JavaScript Error Handling
153
-
154
- **Custom Error Classes:**
155
- ```typescript
156
- // Custom error classes
157
- class ApplicationError extends Error {
158
- constructor(
159
- message: string,
160
- public code: string,
161
- public statusCode: number = 500,
162
- public details?: Record<string, any>
163
- ) {
164
- super(message);
165
- this.name = this.constructor.name;
166
- Error.captureStackTrace(this, this.constructor);
167
- }
168
- }
169
-
170
- class ValidationError extends ApplicationError {
171
- constructor(message: string, details?: Record<string, any>) {
172
- super(message, 'VALIDATION_ERROR', 400, details);
173
- }
174
- }
175
-
176
- class NotFoundError extends ApplicationError {
177
- constructor(resource: string, id: string) {
178
- super(
179
- `${resource} not found`,
180
- 'NOT_FOUND',
181
- 404,
182
- { resource, id }
183
- );
184
- }
185
- }
186
-
187
- // Usage
188
- function getUser(id: string): User {
189
- const user = users.find(u => u.id === id);
190
- if (!user) {
191
- throw new NotFoundError('User', id);
192
- }
193
- return user;
194
- }
195
- ```
196
-
197
- **Result Type Pattern:**
198
- ```typescript
199
- // Result type for explicit error handling
200
- type Result<T, E = Error> =
201
- | { ok: true; value: T }
202
- | { ok: false; error: E };
203
-
204
- // Helper functions
205
- function Ok<T>(value: T): Result<T, never> {
206
- return { ok: true, value };
207
- }
208
-
209
- function Err<E>(error: E): Result<never, E> {
210
- return { ok: false, error };
211
- }
212
-
213
- // Usage
214
- function parseJSON<T>(json: string): Result<T, SyntaxError> {
215
- try {
216
- const value = JSON.parse(json) as T;
217
- return Ok(value);
218
- } catch (error) {
219
- return Err(error as SyntaxError);
220
- }
221
- }
222
-
223
- // Consuming Result
224
- const result = parseJSON<User>(userJson);
225
- if (result.ok) {
226
- console.log(result.value.name);
227
- } else {
228
- console.error('Parse failed:', result.error.message);
229
- }
230
-
231
- // Chaining Results
232
- function chain<T, U, E>(
233
- result: Result<T, E>,
234
- fn: (value: T) => Result<U, E>
235
- ): Result<U, E> {
236
- return result.ok ? fn(result.value) : result;
237
- }
238
- ```
239
-
240
- **Async Error Handling:**
241
- ```typescript
242
- // Async/await with proper error handling
243
- async function fetchUserOrders(userId: string): Promise<Order[]> {
244
- try {
245
- const user = await getUser(userId);
246
- const orders = await getOrders(user.id);
247
- return orders;
248
- } catch (error) {
249
- if (error instanceof NotFoundError) {
250
- return []; // Return empty array for not found
251
- }
252
- if (error instanceof NetworkError) {
253
- // Retry logic
254
- return retryFetchOrders(userId);
255
- }
256
- // Re-throw unexpected errors
257
- throw error;
258
- }
259
- }
260
-
261
- // Promise error handling
262
- function fetchData(url: string): Promise<Data> {
263
- return fetch(url)
264
- .then(response => {
265
- if (!response.ok) {
266
- throw new NetworkError(`HTTP ${response.status}`);
267
- }
268
- return response.json();
269
- })
270
- .catch(error => {
271
- console.error('Fetch failed:', error);
272
- throw error;
273
- });
274
- }
275
- ```
276
-
277
- ### Rust Error Handling
278
-
279
- **Result and Option Types:**
280
- ```rust
281
- use std::fs::File;
282
- use std::io::{self, Read};
283
-
284
- // Result type for operations that can fail
285
- fn read_file(path: &str) -> Result<String, io::Error> {
286
- let mut file = File::open(path)?; // ? operator propagates errors
287
- let mut contents = String::new();
288
- file.read_to_string(&mut contents)?;
289
- Ok(contents)
290
- }
291
-
292
- // Custom error types
293
- #[derive(Debug)]
294
- enum AppError {
295
- Io(io::Error),
296
- Parse(std::num::ParseIntError),
297
- NotFound(String),
298
- Validation(String),
299
- }
300
-
301
- impl From<io::Error> for AppError {
302
- fn from(error: io::Error) -> Self {
303
- AppError::Io(error)
304
- }
305
- }
306
-
307
- // Using custom error type
308
- fn read_number_from_file(path: &str) -> Result<i32, AppError> {
309
- let contents = read_file(path)?; // Auto-converts io::Error
310
- let number = contents.trim().parse()
311
- .map_err(AppError::Parse)?; // Explicitly convert ParseIntError
312
- Ok(number)
313
- }
314
-
315
- // Option for nullable values
316
- fn find_user(id: &str) -> Option<User> {
317
- users.iter().find(|u| u.id == id).cloned()
318
- }
319
-
320
- // Combining Option and Result
321
- fn get_user_age(id: &str) -> Result<u32, AppError> {
322
- find_user(id)
323
- .ok_or_else(|| AppError::NotFound(id.to_string()))
324
- .map(|user| user.age)
325
- }
326
- ```
327
-
328
- ### Go Error Handling
329
-
330
- **Explicit Error Returns:**
331
- ```go
332
- // Basic error handling
333
- func getUser(id string) (*User, error) {
334
- user, err := db.QueryUser(id)
335
- if err != nil {
336
- return nil, fmt.Errorf("failed to query user: %w", err)
337
- }
338
- if user == nil {
339
- return nil, errors.New("user not found")
340
- }
341
- return user, nil
342
- }
343
-
344
- // Custom error types
345
- type ValidationError struct {
346
- Field string
347
- Message string
348
- }
349
-
350
- func (e *ValidationError) Error() string {
351
- return fmt.Sprintf("validation failed for %s: %s", e.Field, e.Message)
352
- }
353
-
354
- // Sentinel errors for comparison
355
- var (
356
- ErrNotFound = errors.New("not found")
357
- ErrUnauthorized = errors.New("unauthorized")
358
- ErrInvalidInput = errors.New("invalid input")
359
- )
360
-
361
- // Error checking
362
- user, err := getUser("123")
363
- if err != nil {
364
- if errors.Is(err, ErrNotFound) {
365
- // Handle not found
366
- } else {
367
- // Handle other errors
368
- }
369
- }
370
-
371
- // Error wrapping and unwrapping
372
- func processUser(id string) error {
373
- user, err := getUser(id)
374
- if err != nil {
375
- return fmt.Errorf("process user failed: %w", err)
376
- }
377
- // Process user
378
- return nil
379
- }
380
-
381
- // Unwrap errors
382
- err := processUser("123")
383
- if err != nil {
384
- var valErr *ValidationError
385
- if errors.As(err, &valErr) {
386
- fmt.Printf("Validation error: %s\n", valErr.Field)
387
- }
388
- }
389
- ```
390
-
391
- ## Universal Patterns
392
-
393
- ### Pattern 1: Circuit Breaker
394
-
395
- Prevent cascading failures in distributed systems.
396
-
397
- ```python
398
- from enum import Enum
399
- from datetime import datetime, timedelta
400
- from typing import Callable, TypeVar
401
-
402
- T = TypeVar('T')
403
-
404
- class CircuitState(Enum):
405
- CLOSED = "closed" # Normal operation
406
- OPEN = "open" # Failing, reject requests
407
- HALF_OPEN = "half_open" # Testing if recovered
408
-
409
- class CircuitBreaker:
410
- def __init__(
411
- self,
412
- failure_threshold: int = 5,
413
- timeout: timedelta = timedelta(seconds=60),
414
- success_threshold: int = 2
415
- ):
416
- self.failure_threshold = failure_threshold
417
- self.timeout = timeout
418
- self.success_threshold = success_threshold
419
- self.failure_count = 0
420
- self.success_count = 0
421
- self.state = CircuitState.CLOSED
422
- self.last_failure_time = None
423
-
424
- def call(self, func: Callable[[], T]) -> T:
425
- if self.state == CircuitState.OPEN:
426
- if datetime.now() - self.last_failure_time > self.timeout:
427
- self.state = CircuitState.HALF_OPEN
428
- self.success_count = 0
429
- else:
430
- raise Exception("Circuit breaker is OPEN")
431
-
432
- try:
433
- result = func()
434
- self.on_success()
435
- return result
436
- except Exception as e:
437
- self.on_failure()
438
- raise
439
-
440
- def on_success(self):
441
- self.failure_count = 0
442
- if self.state == CircuitState.HALF_OPEN:
443
- self.success_count += 1
444
- if self.success_count >= self.success_threshold:
445
- self.state = CircuitState.CLOSED
446
- self.success_count = 0
447
-
448
- def on_failure(self):
449
- self.failure_count += 1
450
- self.last_failure_time = datetime.now()
451
- if self.failure_count >= self.failure_threshold:
452
- self.state = CircuitState.OPEN
453
-
454
- # Usage
455
- circuit_breaker = CircuitBreaker()
456
-
457
- def fetch_data():
458
- return circuit_breaker.call(lambda: external_api.get_data())
459
- ```
460
-
461
- ### Pattern 2: Error Aggregation
462
-
463
- Collect multiple errors instead of failing on first error.
464
-
465
- ```typescript
466
- class ErrorCollector {
467
- private errors: Error[] = [];
468
-
469
- add(error: Error): void {
470
- this.errors.push(error);
471
- }
472
-
473
- hasErrors(): boolean {
474
- return this.errors.length > 0;
475
- }
476
-
477
- getErrors(): Error[] {
478
- return [...this.errors];
479
- }
480
-
481
- throw(): never {
482
- if (this.errors.length === 1) {
483
- throw this.errors[0];
484
- }
485
- throw new AggregateError(
486
- this.errors,
487
- `${this.errors.length} errors occurred`
488
- );
489
- }
490
- }
491
-
492
- // Usage: Validate multiple fields
493
- function validateUser(data: any): User {
494
- const errors = new ErrorCollector();
495
-
496
- if (!data.email) {
497
- errors.add(new ValidationError('Email is required'));
498
- } else if (!isValidEmail(data.email)) {
499
- errors.add(new ValidationError('Email is invalid'));
500
- }
501
-
502
- if (!data.name || data.name.length < 2) {
503
- errors.add(new ValidationError('Name must be at least 2 characters'));
504
- }
505
-
506
- if (!data.age || data.age < 18) {
507
- errors.add(new ValidationError('Age must be 18 or older'));
508
- }
509
-
510
- if (errors.hasErrors()) {
511
- errors.throw();
512
- }
513
-
514
- return data as User;
515
- }
516
- ```
517
-
518
- ### Pattern 3: Graceful Degradation
519
-
520
- Provide fallback functionality when errors occur.
521
-
522
- ```python
523
- from typing import Optional, Callable, TypeVar
524
-
525
- T = TypeVar('T')
526
-
527
- def with_fallback(
528
- primary: Callable[[], T],
529
- fallback: Callable[[], T],
530
- log_error: bool = True
531
- ) -> T:
532
- """Try primary function, fall back to fallback on error."""
533
- try:
534
- return primary()
535
- except Exception as e:
536
- if log_error:
537
- logger.error(f"Primary function failed: {e}")
538
- return fallback()
539
-
540
- # Usage
541
- def get_user_profile(user_id: str) -> UserProfile:
542
- return with_fallback(
543
- primary=lambda: fetch_from_cache(user_id),
544
- fallback=lambda: fetch_from_database(user_id)
545
- )
546
-
547
- # Multiple fallbacks
548
- def get_exchange_rate(currency: str) -> float:
549
- return (
550
- try_function(lambda: api_provider_1.get_rate(currency))
551
- or try_function(lambda: api_provider_2.get_rate(currency))
552
- or try_function(lambda: cache.get_rate(currency))
553
- or DEFAULT_RATE
554
- )
555
-
556
- def try_function(func: Callable[[], Optional[T]]) -> Optional[T]:
557
- try:
558
- return func()
559
- except Exception:
560
- return None
561
- ```
562
-
563
- ## Best Practices
564
-
565
- 1. **Fail Fast**: Validate input early, fail quickly
566
- 2. **Preserve Context**: Include stack traces, metadata, timestamps
567
- 3. **Meaningful Messages**: Explain what happened and how to fix it
568
- 4. **Log Appropriately**: Error = log, expected failure = don't spam logs
569
- 5. **Handle at Right Level**: Catch where you can meaningfully handle
570
- 6. **Clean Up Resources**: Use try-finally, context managers, defer
571
- 7. **Don't Swallow Errors**: Log or re-throw, don't silently ignore
572
- 8. **Type-Safe Errors**: Use typed errors when possible
573
-
574
- ```python
575
- # Good error handling example
576
- def process_order(order_id: str) -> Order:
577
- """Process order with comprehensive error handling."""
578
- try:
579
- # Validate input
580
- if not order_id:
581
- raise ValidationError("Order ID is required")
582
-
583
- # Fetch order
584
- order = db.get_order(order_id)
585
- if not order:
586
- raise NotFoundError("Order", order_id)
587
-
588
- # Process payment
589
- try:
590
- payment_result = payment_service.charge(order.total)
591
- except PaymentServiceError as e:
592
- # Log and wrap external service error
593
- logger.error(f"Payment failed for order {order_id}: {e}")
594
- raise ExternalServiceError(
595
- f"Payment processing failed",
596
- service="payment_service",
597
- details={"order_id": order_id, "amount": order.total}
598
- ) from e
599
-
600
- # Update order
601
- order.status = "completed"
602
- order.payment_id = payment_result.id
603
- db.save(order)
604
-
605
- return order
606
-
607
- except ApplicationError:
608
- # Re-raise known application errors
609
- raise
610
- except Exception as e:
611
- # Log unexpected errors
612
- logger.exception(f"Unexpected error processing order {order_id}")
613
- raise ApplicationError(
614
- "Order processing failed",
615
- code="INTERNAL_ERROR"
616
- ) from e
617
- ```
618
-
619
- ## Common Pitfalls
620
-
621
- - **Catching Too Broadly**: `except Exception` hides bugs
622
- - **Empty Catch Blocks**: Silently swallowing errors
623
- - **Logging and Re-throwing**: Creates duplicate log entries
624
- - **Not Cleaning Up**: Forgetting to close files, connections
625
- - **Poor Error Messages**: "Error occurred" is not helpful
626
- - **Returning Error Codes**: Use exceptions or Result types
627
- - **Ignoring Async Errors**: Unhandled promise rejections
628
-
629
- ## Resources
630
-
631
- - **references/exception-hierarchy-design.md**: Designing error class hierarchies
632
- - **references/error-recovery-strategies.md**: Recovery patterns for different scenarios
633
- - **references/async-error-handling.md**: Handling errors in concurrent code
634
- - **assets/error-handling-checklist.md**: Review checklist for error handling
635
- - **assets/error-message-guide.md**: Writing helpful error messages
636
- - **scripts/error-analyzer.py**: Analyze error patterns in logs