ddp_utils.errors¶
import ddp_utils.errors
Provide error logging, screenshots, exception boundaries, and retries.
The module keeps default error and screenshot paths in ddp_utils.globals,
can capture the active traceback, offers recoverable and terminating exception
types, and supplies decorators for exception logging and retry backoff.
Examples
Configure a shared error file and log a handled failure:
from ddp_utils.errors import set_error_file, stderr_log
set_error_file(".runtime/errors/project.err")
try:
raise RuntimeError("request failed")
except RuntimeError:
stderr_log("API request", exit=False)
- ddp_utils.errors.set_error_file(file: str | PathLike) None¶
Store the default destination for subsequent error log records.
The path is placed in
ddp_utils.globalsundererr_file. Calls such asstderr_log()use it when no expliciterr_fileis given.Parameters
Name
Type
Description
file
str | PathLike
String or path-like error-log destination.
Examples
Configure the process-wide default error file:
set_error_file("logs/project.err")
- ddp_utils.errors.set_screenshot_file(file: str | PathLike, timestamp: bool = True) None¶
Store the default destination for error screenshots.
When
timestampis true, the current time is appended to the supplied stem before the suffix. A missing suffix is treated as.png.Parameters
Name
Type
Description
file
str | PathLike
String or path-like screenshot destination.
timestamp
bool
Whether to append the current time to the filename.
Examples
Preserve the exact configured filename:
set_screenshot_file("logs/failure.png", timestamp=False)
- ddp_utils.errors.do_screenshot_on_error(default: bool = False) None¶
Set the default screenshot policy used by
stderr_log().Parameters
Name
Type
Description
default
bool
Whether calls without an override should capture a screenshot.
Examples
Enable screenshots globally while retaining per-call overrides:
do_screenshot_on_error(True) stderr_log("Validation", "invalid record", exit=False)
- ddp_utils.errors.take_screenshot(file: str | PathLike | None = None) str | None¶
Capture the desktop and save it to a configured image file.
pyautoguiis imported only when capture is requested. Parent directories are created before the image is saved.Parameters
Name
Type
Description
file
str | PathLike | None
Destination path, or
Noneto use the global default.Returns
Type
Description
str | None
Saved path text, or
Nonewhen no destination is configured.Raises
Exception
Description
ImportError
pyautoguiis unavailable when capture is attempted.OSError
The destination cannot be created or written.
Examples
Capture to an explicit destination:
saved_path = take_screenshot("artifacts/failure.png")
- ddp_utils.errors.stderr_log(ttl: str = '', error: str | Any = '', *, exit: bool = True, err_file: str | PathLike | None = None, screenshot_file: str | PathLike | None = None, on_exit: Callable[[], Any] | None = None, exit_code: int = 1, print_console: bool = True, do_screenshot: bool | None = None) None¶
Record the active traceback or supplied error and optionally exit.
The active exception traceback takes precedence over
error. Output can be appended to a file, printed to the console, accompanied by a desktop screenshot, and followed by cleanup plusSystemExit. Failures in optional screenshot, file, or cleanup operations are reported to stdout without replacing the original error record.Parameters
Name
Type
Description
ttl
str
Optional title written with a timestamp before the error body.
error
str | Any
Fallback error object or text when no traceback is active.
exit
bool
Whether to terminate after recording the error.
err_file
str | PathLike | None
Per-call log path, or
Noneto use the global default.screenshot_file
str | PathLike | None
Explicit screenshot path. Without it, the path is derived from
err_fileand then from the global default.on_exit
Callable[[], Any] | None
Optional zero-argument cleanup callback invoked before exit.
exit_code
int
Status supplied to
sys.exit().print_console
bool
Whether to write the title and body to stdout.
do_screenshot
bool | None
Per-call screenshot policy, or
Nonefor the globalscreenshot_on_errorsetting.Raises
Exception
Description
SystemExit
exitis true after logging and optional cleanup.Examples
Preserve a current traceback without terminating:
try: 1 / 0 except ZeroDivisionError: stderr_log("Division failed", exit=False)
Record a fatal message and run cleanup before exiting:
stderr_log( "Engine crash", "browser became unavailable", err_file="engine.err", on_exit=close_resources, exit=True, )
- exception ddp_utils.errors.StdErrorRuntime(ttl: str = 'Runtime error', error: str | Any = '')¶
Bases:
RuntimeErrorRepresent a recoverable project-layer failure without side effects.
Construction does not log, capture a screenshot, or terminate the process. When created inside an active
exceptblock, the handled exception is attached as__cause__so a later process boundary can retain context.Parameters
Name
Type
Description
ttl
str
Short failure title or operation context.
error
Union[str, Any]
Message, exception, or object appended to the title.
Examples
Raise a structured runtime failure for an outer boundary to handle:
raise StdErrorRuntime("Configuration", "missing browser path")
Initialize the title, payload, optional cause, and final message.
Parameters
Name
Type
Description
ttl
str
Short failure title or operation context.
error
Union[str, Any]
Message, exception, or object appended to the title.
Examples
Create an exception without logging or exiting:
failure = StdErrorRuntime("Network", "request timed out")
- exception ddp_utils.errors.StdErrorException(ttl='Exception Raise', error: str | Any = '')¶
Bases:
ExceptionLog a fatal error during construction and terminate the process.
Unlike
StdErrorRuntime, construction immediately callsstderr_log()withexit=True. If construction occurs while another exception is handled, that exception is attached as__cause__.Parameters
Name
Type
Description
ttl
Short fatal-error title or operation context.
error
Union[str, Any]
Message, exception, or object recorded as the error body.
Raises
Exception
Description
SystemExit
Always raised by
stderr_log()during construction.Examples
Convert a caught unrecoverable failure into a logged process exit:
try: start_required_service() except RuntimeError: StdErrorException("Service startup", "service unavailable")
Initialize the exception, preserve a cause, log, and exit.
Parameters
Name
Type
Description
ttl
Short fatal-error title or operation context.
error
Union[str, Any]
Message, exception, or object recorded as the error body.
Raises
Exception
Description
SystemExit
Always raised after the fatal error is recorded.
Examples
Terminate with a configured fatal-error record:
StdErrorException("Bootstrap", "license is unavailable")
- ddp_utils.errors.catch_and_log(ttl: str = '', *, fallback: Any = None, reraise: bool = False, err_file: str | PathLike | None = None, exit_on_error: bool = False, do_screenshot: bool | None = None) Callable¶
Decorate a callable to log handled exceptions and apply a policy.
A matching failure is recorded through
stderr_log(). The wrapper then re-raises it, returnsfallback, or terminates whenexit_on_erroris enabled.Parameters
Name
Type
Description
ttl
str
Error title, or an empty string to use the callable’s qualified name.
fallback
Any
Value returned after logging when the exception is suppressed.
reraise
bool
Whether to re-raise the original exception after logging.
err_file
str | PathLike | None
Optional per-decorator error-log destination.
exit_on_error
bool
Whether logging should terminate through
SystemExit.do_screenshot
bool | None
Screenshot override, or
Nonefor the global policy.Returns
Type
Description
Callable
Decorator that preserves the wrapped callable’s metadata.
Raises
Exception
Description
SystemExit
A wrapped call fails while
exit_on_erroris true.Examples
Return an empty collection after logging a failed load:
@catch_and_log("Data loader", fallback=[], err_file="errors.log") def load_data(path): return path.read_text(encoding="utf-8")
- ddp_utils.errors.error_context(name: str, *, reraise: bool = True, err_file: str | PathLike | None = None, do_screenshot: bool | None = None)¶
Log exceptions escaping a named context and optionally suppress them.
Parameters
Name
Type
Description
name
str
Context name used as the error-log title.
reraise
bool
Whether to re-raise the original exception after logging.
err_file
str | PathLike | None
Optional error-log destination for this context.
do_screenshot
bool | None
Screenshot override, or
Nonefor the global policy.Returns
Context manager yielding no value.
Raises
Exception
Description
Exception
The original exception when
reraiseis true.Examples
Log and suppress failure at an optional API boundary:
with error_context("Optional API", reraise=False, err_file="api.err"): call_optional_api()
- ddp_utils.errors.retry_on_exception(attempts: int = 3, delay: float = 1.0, backoff: float = 2.0, max_delay: float = 60.0, exceptions: ~typing.Tuple[~typing.Type[Exception], ...] = (<class 'Exception'>,), on_retry: ~typing.Callable[[int, Exception], None] | None = None) Callable¶
Retry selected exceptions using bounded exponential backoff.
The first call is immediate. Between failed attempts, the delay is capped by
max_delayand then multiplied bybackofffor the next retry. Failures raised byon_retryare deliberately ignored.Parameters
Name
Type
Description
attempts
int
Maximum total invocation count, including the initial call.
delay
float
Initial pause in seconds after the first failed attempt.
backoff
float
Multiplier applied to the delay after each retry.
max_delay
float
Maximum individual sleep duration in seconds.
exceptions
Tuple[Type[Exception], ...]
Exception classes that trigger another attempt.
on_retry
Callable[[int, Exception], None] | None
Optional callback receiving the failed attempt number and exception before the sleep.
Returns
Type
Description
Callable
Decorator that applies retry behavior to a callable.
Raises
Exception
Description
Exception
The last captured exception after all attempts fail.
Examples
Retry transient connection failures up to three times:
@retry_on_exception( attempts=3, delay=0.5, exceptions=(ConnectionError, TimeoutError), ) def fetch_data(): return client.fetch()