Errors & debugging
Handle failures gracefully, raise helpful errors, and debug with confidence.
Collect Multiple Validation Errors in Python Before Raising
A chainable Validator class that accumulates all validation errors and raises them together in a single exception.
class ValidationError(Exception):
pass
class Validator:
def __init__(self):
self.errors = []
def validate_required(self, value, field_name):
if not value:
self.errors.append(f"{field_name} is required")
return self
def validate_email(self, email):
…
How to Add a Correlation ID to Logging Records in Python
Attach a unique correlation ID to every log record using a custom logging.Filter, making distributed request tracking traceable.
import logging
import uuid
from dataclasses import dataclass, field
@dataclass
class CorrelationIdFilter(logging.Filter):
correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
def filter(self, record: logging.LogRecord) -> bool:
record.correlation_id = self.correlation_id
re…
How to Diff Two Dicts in Python for Config Drift
Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.
def diff_dicts(a, b, path=""):
differences = []
for key in a.keys() | b.keys():
new_path = f"{path}.{key}" if path else key
if key not in a:
differences.append((new_path, "<missing>", b[key], "added"))
elif key not in b:
differences.append((new_path, a[key], "<…
How to Log Errors with Structured Fields in Python
Logs error details as structured dictionary fields using Python's logging module with extra parameters.
import logging
import sys
def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
"""Log an error with structured fields using a dictionary."""
logger = logging.getLogger("structured_logger")
logger.setLevel(logging.ERROR)
# Create console handler if not already …
How to Print an Exception Chain in Python for Debugging
A helper that walks an exception's __cause__ and __context__ chain, printing each level with indentation to make debugging nested errors clearer.
import sys
import traceback
def pretty_exception_chain(exc):
"""Print the full exception chain with cause/context details."""
chain = []
current = exc
seen = set()
while current is not None and id(current) not in seen:
seen.add(id(current))
chain.append(current)
curren…
How to Re-raise Exceptions with 'raise from' in Python
Shows how to re-raise an exception with explicit context chaining using the 'raise ... from ...' syntax, so the original cause is preserved for debugging.
def divide_with_chain(a, b):
try:
result = a / b
return result
except ZeroDivisionError as original_error:
# Re-raise with explicit chaining context
raise ValueError("Cannot divide by zero") from original_error
def explain_chain():
try:
divide_with_chain(10, 0)
…
How to Simulate Timeout with Custom TimeoutError in Python
Run a function in a daemon thread and raise a custom TimeoutError if it exceeds a specified time limit.
import time
from typing import Callable, TypeVar
T = TypeVar("T")
class TimeoutError(Exception):
"""Raised when an operation exceeds its time limit."""
def __init__(self, message: str = "Operation timed out"):
self.message = message
super().__init__(self.message)
def run_with_timeout(func…
How to attach a request ID to exception messages in Python
This code shows how to enrich exception messages with contextual request IDs using context variables, making error logs more traceable across concurrent requests.
import logging
from contextvars import ContextVar
request_id_var = ContextVar("request_id", default="unknown")
def add_request_id(exc: Exception) -> Exception:
exc.args = (f"request_id={request_id_var.get()} | {exc.args[0]}" if exc.args else f"request_id={request_id_var.get()}",) + exc.args[1:]
return exc
d…
How to parse a traceback to get the last frame in Python
Extracts the innermost frame's file, line, and function name from a Python traceback object.
import sys
import traceback
def parse_traceback_last_frame(exc_info):
"""Return the file, line, and function of the last (innermost) frame."""
_, _, tb = exc_info
last_tb = tb
while last_tb.tb_next is not None:
last_tb = last_tb.tb_next
filename = last_tb.tb_frame.f_code.co_filename
l…
Implement circuit breaker open after failures demo in Python
A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.
import time
from datetime import datetime
class CircuitBreaker:
def __init__(self, threshold=3):
self.threshold = threshold
self.failure_count = 0
self.is_open = False
def call(self, func, *args, **kwargs):
if self.is_open:
raise RuntimeError("Circuit is OPEN")
…
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
Browse by section
Each section groups closely related Python snippets.
Errors & debugging — Python code examples
What you will find here
This page collects errors & debugging snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.