示例工程 30-plugin-registry-design

30-plugin-registry-design/04-plugin-failure-isolation/plugin_failure_isolation.py

python · 0.9 KB

"""插件失败隔离:一个插件坏掉,不影响其他插件。"""
 
from __future__ import annotations
 
from collections.abc import Callable
 
 
def ok() -> str:
    return "ok"
 
 
def bad() -> str:
    raise RuntimeError("boom")
 
 
def missing() -> str:
    raise KeyError("missing")
 
 
PLUGINS: dict[str, Callable[[], str]] = {"ok": ok, "bad": bad, "missing": missing}
 
 
def run_all(
    plugins: dict[str, Callable[[], str]],
) -> tuple[dict[str, str], dict[str, str]]:
    results: dict[str, str] = {}
    errors: dict[str, str] = {}
    for name, plugin in plugins.items():
        try:
            results[name] = plugin()
        except Exception as exc:
            errors[name] = f"{type(exc).__name__}: {exc}"
    return results, errors
 
 
def main() -> None:
    results, errors = run_all(PLUGINS)
    print(f"results: {results}")
    print(f"errors: {errors}")
 
 
if __name__ == "__main__":
    main()