← Lesson
Error Recovery
Joeven
Run
Reset
Python loads on first run
class CircuitBreaker: def __init__(self, fail_max=2): self.fail_max = fail_max self.fails = 0 self.open = False def call(self, fn): if self.open: return {"error": "circuit_open"} try: out = fn() self.fails = 0 return {"ok": out} except Exception as e: self.fails += 1 if self.fails >= self.fail_max: self.open = True return {"error": str(e), "fails": self.fails} n = {"i": 0} def flaky(): n["i"] += 1 if n["i"] < 3: raise RuntimeError("timeout") return "ok" br = CircuitBreaker(fail_max=2) print(br.call(flaky)) print(br.call(flaky)) print(br.call(flaky))
Run to execute this in your browser. Nothing is sent to a server.