Error Handling
Skill Profile
(Select at least one profile to enable specific modules)
Overview
Error Handling is a critical component of backend development that enables applications to operate reliably, maintainably, and debuggably. It encompasses patterns and best practices for handling, logging, and monitoring errors.
Error Handling consists of:
- Error Classification - Distinguishing error types (operational vs programmer errors)
- Custom Error Classes - Creating domain-specific error classes
- Error Middleware - Global error handlers for consistent responses
- Error Logging - Logging errors for debugging and monitoring
- Error Monitoring - External monitoring services (Sentry, etc.)
- Error Recovery - Retry, fallback, and circuit breaker patterns
Why This Matters
- Reduce Downtime: Proper error handling can reduce downtime by 40-60%
- Improve User Experience: Graceful error handling enhances UX
- Reduce Debugging Time: Structured error logging reduces debugging time
- Increase Maintainability: Consistent error handling improves maintainability
- Enhance Reliability: Error recovery patterns increase reliability
Core Concepts & Rules
1. Core Principles
- Follow established patterns and conventions
- Maintain consistency across codebase
- Document decisions and trade-offs
2. Implementation Guidelines
- Start with the simplest viable solution
- Iterate based on feedback and requirements
- Test thoroughly before deployment
Inputs / Outputs / Contracts
- Inputs:
- Error requirements
- Logging requirements
- Monitoring requirements
- Recovery strategy
- Entry Conditions:
- Backend framework is set up
- Logging library is installed
- Monitoring service is configured
- Error handling strategy is defined
- Outputs:
- Custom error classes
- Error middleware
- Logging configuration
- Monitoring setup
- Recovery patterns
- Artifacts Required (Deliverables):
- Error class hierarchy
- Error middleware
- Logging configuration
- Monitoring integration
- Recovery utilities
- Acceptance Evidence:
- Errors are handled consistently
- Logging is structured
- Monitoring captures errors
- Recovery patterns work
- Success Criteria:
- Error handling is robust
- Logging is comprehensive
- Monitoring is effective
- Recovery patterns work
Skill Composition
Quick Start / Implementation Example
- Review requirements and constraints
- Set up development environment
- Implement core functionality following patterns
- Write tests for critical paths
- Run tests and fix issues
- Document any deviations or decisions
# Example implementation following best practices
def example_function():
# Your implementation here
pass
Assumptions / Constraints / Non-goals
- Assumptions:
- Development environment is properly configured
- Required dependencies are available
- Team has basic understanding of domain
- Constraints:
- Must follow existing codebase conventions
- Time and resource limitations
- Compatibility requirements
- Non-goals:
- This skill does not cover edge cases outside scope
- Not a replacement for formal training
Compatibility & Prerequisites
- Supported Versions:
- Python 3.8+
- Node.js 16+
- Modern browsers (Chrome, Firefox, Safari, Edge)
- Required AI Tools:
- Code editor (VS Code recommended)
- Testing framework appropriate for language
- Version control (Git)
- Dependencies:
- Language-specific package manager
- Build tools
- Testing libraries
- Environment Setup:
.env.example keys: API_KEY, DATABASE_URL (no values)
Test Scenario Matrix (QA Strategy)
| Type |
Focus Area |
Required Scenarios / Mocks |
| Unit |
Core Logic |
Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |
| Integration |
DB / API |
All external API calls or database connections must be mocked during unit tests |
| E2E |
User Journey |
Critical user flows to test |
| Performance |
Latency / Load |
Benchmark requirements |
| Security |
Vuln / Auth |
SAST/DAST or dependency audit |
| Frontend |
UX / A11y |
Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |
Technical Guardrails & Security Threat Model
1. Security & Privacy (Threat Model)
- Top Threats: Injection attacks, authentication bypass, data exposure
2. Performance & Resources
3. Architecture & Scalability
4. Observability & Reliability
Agent Directives & Error Recovery
(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)
- Thinking Process: Analyze root cause before fixing. Do not brute-force.
- Fallback Strategy: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.
- Self-Review: Check against Guardrails & Anti-patterns before finalizing.
- Output Constraints: Output ONLY the modified code block. Do not explain unless asked.
Definition of Done (DoD) Checklist
Anti-patterns / Pitfalls
- ⛔ Don't: Log PII, catch-all exception, N+1 queries
- ⚠️ Watch out for: Common symptoms and quick fixes
- 💡 Instead: Use proper error handling, pagination, and logging
Reference Links & Examples
- Internal documentation and examples
- Official documentation and best practices
- Community resources and discussions
Versioning & Changelog
- Version: 1.0.0
- Changelog:
- 2026-02-22: Initial version with complete template structure
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: error-handling-73description: Error Handling is a critical component of backend development that enables Use when this capability is needed.4---56# Error Handling78## Skill Profile9*(Select at least one profile to enable specific modules)*10- [ ] **DevOps**11- [x] **Backend**12- [ ] **Frontend**13- [ ] **AI-RAG**14- [ ] **Security Critical**1516## Overview17Error Handling is a critical component of backend development that enables applications to operate reliably, maintainably, and debuggably. It encompasses patterns and best practices for handling, logging, and monitoring errors.1819Error Handling consists of:20- **Error Classification** - Distinguishing error types (operational vs programmer errors)21- **Custom Error Classes** - Creating domain-specific error classes22- **Error Middleware** - Global error handlers for consistent responses23- **Error Logging** - Logging errors for debugging and monitoring24- **Error Monitoring** - External monitoring services (Sentry, etc.)25- **Error Recovery** - Retry, fallback, and circuit breaker patterns2627## Why This Matters28- **Reduce Downtime**: Proper error handling can reduce downtime by 40-60%29- **Improve User Experience**: Graceful error handling enhances UX30- **Reduce Debugging Time**: Structured error logging reduces debugging time31- **Increase Maintainability**: Consistent error handling improves maintainability32- **Enhance Reliability**: Error recovery patterns increase reliability3334---3536## Core Concepts & Rules3738### 1. Core Principles39- Follow established patterns and conventions40- Maintain consistency across codebase41- Document decisions and trade-offs4243### 2. Implementation Guidelines44- Start with the simplest viable solution45- Iterate based on feedback and requirements46- Test thoroughly before deployment474849## Inputs / Outputs / Contracts50* **Inputs**:51 - Error requirements52 - Logging requirements53 - Monitoring requirements54 - Recovery strategy55* **Entry Conditions**:56 - Backend framework is set up57 - Logging library is installed58 - Monitoring service is configured59 - Error handling strategy is defined60* **Outputs**:61 - Custom error classes62 - Error middleware63 - Logging configuration64 - Monitoring setup65 - Recovery patterns66* **Artifacts Required (Deliverables)**:67 - Error class hierarchy68 - Error middleware69 - Logging configuration70 - Monitoring integration71 - Recovery utilities72* **Acceptance Evidence**:73 - Errors are handled consistently74 - Logging is structured75 - Monitoring captures errors76 - Recovery patterns work77* **Success Criteria**:78 - Error handling is robust79 - Logging is comprehensive80 - Monitoring is effective81 - Recovery patterns work8283## Skill Composition84* **Depends on**: [api-design](../../01-foundations/api-design/SKILL.md), [middleware](../middleware/SKILL.md)85* **Compatible with**: [validation](../validation/SKILL.md), [express-rest](../express-rest/SKILL.md), [fastapi-patterns](../fastapi-patterns/SKILL.md)86* **Conflicts with**: None87* **Related Skills**: [monitoring-observability](../../14-monitoring-observability/SKILL.md), [testing](../../16-testing/SKILL.md)8889---9091## Quick Start / Implementation Example92931. Review requirements and constraints942. Set up development environment953. Implement core functionality following patterns964. Write tests for critical paths975. Run tests and fix issues986. Document any deviations or decisions99100```python101# Example implementation following best practices102def example_function():103 # Your implementation here104 pass105```106107108## Assumptions / Constraints / Non-goals109110* **Assumptions**:111 - Development environment is properly configured112 - Required dependencies are available113 - Team has basic understanding of domain114* **Constraints**:115 - Must follow existing codebase conventions116 - Time and resource limitations117 - Compatibility requirements118* **Non-goals**:119 - This skill does not cover edge cases outside scope120 - Not a replacement for formal training121122123## Compatibility & Prerequisites124125* **Supported Versions**:126 - Python 3.8+127 - Node.js 16+128 - Modern browsers (Chrome, Firefox, Safari, Edge)129* **Required AI Tools**:130 - Code editor (VS Code recommended)131 - Testing framework appropriate for language132 - Version control (Git)133* **Dependencies**:134 - Language-specific package manager135 - Build tools136 - Testing libraries137* **Environment Setup**:138 - `.env.example` keys: `API_KEY`, `DATABASE_URL` (no values)139140141## Test Scenario Matrix (QA Strategy)142143| Type | Focus Area | Required Scenarios / Mocks |144| :--- | :--- | :--- |145| **Unit** | Core Logic | Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |146| **Integration** | DB / API | All external API calls or database connections must be mocked during unit tests |147| **E2E** | User Journey | Critical user flows to test |148| **Performance** | Latency / Load | Benchmark requirements |149| **Security** | Vuln / Auth | SAST/DAST or dependency audit |150| **Frontend** | UX / A11y | Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |151152153## Technical Guardrails & Security Threat Model154155### 1. Security & Privacy (Threat Model)156* **Top Threats**: Injection attacks, authentication bypass, data exposure157- [ ] **Data Handling**: Sanitize all user inputs to prevent Injection attacks. Never log raw PII158- [ ] **Secrets Management**: No hardcoded API keys. Use Env Vars/Secrets Manager159- [ ] **Authorization**: Validate user permissions before state changes160161### 2. Performance & Resources162- [ ] **Execution Efficiency**: Consider time complexity for algorithms163- [ ] **Memory Management**: Use streams/pagination for large data164- [ ] **Resource Cleanup**: Close DB connections/file handlers in finally blocks165166### 3. Architecture & Scalability167- [ ] **Design Pattern**: Follow SOLID principles, use Dependency Injection168- [ ] **Modularity**: Decouple logic from UI/Frameworks169170### 4. Observability & Reliability171- [ ] **Logging Standards**: Structured JSON, include trace IDs `request_id`172- [ ] **Metrics**: Track `error_rate`, `latency`, `queue_depth`173- [ ] **Error Handling**: Standardized error codes, no bare except174- [ ] **Observability Artifacts**:175 - **Log Fields**: timestamp, level, message, request_id176 - **Metrics**: request_count, error_count, response_time177 - **Dashboards/Alerts**: High Error Rate > 5%178179180## Agent Directives & Error Recovery181*(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)*182183- **Thinking Process**: Analyze root cause before fixing. Do not brute-force.184- **Fallback Strategy**: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.185- **Self-Review**: Check against Guardrails & Anti-patterns before finalizing.186- **Output Constraints**: Output ONLY the modified code block. Do not explain unless asked.187188189## Definition of Done (DoD) Checklist190191- [ ] Tests passed + coverage met192- [ ] Lint/Typecheck passed193- [ ] Logging/Metrics/Trace implemented194- [ ] Security checks passed195- [ ] Documentation/Changelog updated196- [ ] Accessibility/Performance requirements met (if frontend)197198199## Anti-patterns / Pitfalls200201* ⛔ **Don't**: Log PII, catch-all exception, N+1 queries202* ⚠️ **Watch out for**: Common symptoms and quick fixes203* 💡 **Instead**: Use proper error handling, pagination, and logging204205206## Reference Links & Examples207208* Internal documentation and examples209* Official documentation and best practices210* Community resources and discussions211212213## Versioning & Changelog214215* **Version**: 1.0.0216* **Changelog**:217 - 2026-02-22: Initial version with complete template structure218219---220> Converted and distributed by [TomeVault](https://tomevault.io/claim/amnadtaowsoam) — claim your Tome and manage your conversions.221<!-- tomevault:4.0:skill_md:2026-04-13 -->