🛡️ Error Handling Skill
Context
An application "functioning to perfection" means it NEVER crashes unconditionally. It manages errors gracefully.
1. Hierarchy of Exceptions
Define custom exceptions in src/core/exceptions.py.
python
class AppError(Exception):
"""Base class for all application errors."""
pass
class ServiceError(AppError):
"""Errors in the service layer."""
pass
class UIError(AppError):
"""Errors in the UI layer."""
pass
2. The Safe UI Decorator
NEVER let an exception crash the GUI thread. Use a decorator for event handlers.
python
import functools
import wxcustom # Hypothetical util
from src.core.logging import get_logger
logger = get_logger(__name__)
def safe_event(func):
"""Swallows exceptions and shows an Error Dialog."""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Exception as e:
logger.exception("Uncaught UI Error")
wx.MessageBox(f"An unexpected error occurred: {e}", "Error", wx.ICON_ERROR)
return wrapper
3. Boundary Pattern
Service layers should catch low-level exceptions (e.g., requests.exceptions.ConnectionError) and re-raise them as domain exceptions (NetworkError), preserving the stack trace (raise ... from e).
python
def fetch_data():
try:
http_client.get(...)
except RequestException as e:
logger.error("Failed to fetch data")
raise ServiceError("Could not retrieve data") from e
4. Checklist
- • Are UI event handlers decorated/protected?
- • Are we using
logger.exception()in catch blocks? - • Are we re-raising with context (
from e)?