Skip to content

gufo.err

Human-readable error reporting.

Attributes:

Name Type Description
__version__ str

Current version.

HAS_CODE_POSITION

True, if Python interpreter supports exact code positions (Python 3.11+)

Anchor dataclass

Bases: object

Exact problem position (Python 3.11+).

Denotes operator of subscript which causes the problem.

Parameters:

Name Type Description Default
left int

Starting column.

required
right int

Stopping column.

required

BaseFailFast

Bases: ABC

Abstract base type for fail-fast behavior.

Fail-fast classes must implement must_die method. When fail-fast check decides the error is unrecoverable, it must return True value.

must_die(t, v, tb) abstractmethod

Fail-fast check. Must be overriden in subclasses.

Parameters:

Name Type Description Default
t Type[BaseException]

Exception type. Same as sys.exc_info()[0].

required
v BaseException

Exception value. Same as sys.exc_info()[1].

required
tb TracebackType

Traceback. Same as sys.exc_info()[2].

required

Returns:

Type Description
bool
  • True, if the error is not recoverable and the process
bool

must be terminated ASAP.

bool
  • False to pass to the next check.

BaseMiddleware

Bases: ABC

Abstract base type for error processing middleware.

Middleware must implement process method.

process(info) abstractmethod

Process the error.

Parameters:

Name Type Description Default
info ErrorInfo

ErrorInfo instance with detailed error information.

required

CodePosition dataclass

Bases: object

Exact code position for Python 3.11+.

Parameters:

Name Type Description Default
start_line int

First line of code

required
end_line int

Last line of code

required
start_col int

Starting column (on start_line)

required
end_col int

Ending column (on end_line)

required
anchor Optional[Anchor]

Problem anchor

required

Err

Bases: object

Error handling singleton.

Example
from gufo.err import err

err.setup()

__default_middleware(format=None, error_info_path=None, error_info_compress=None)

Get default middleware chain.

Parameters:

Name Type Description Default
format Optional[str]

traceback format. See TracebackMiddleware for details. Do not configure tracebacks if None.

None
error_info_path Optional[str]

Directory path to write error info. See ErrorInfoMiddleware for details. Do not configure middleware if None.

None
error_info_compress Optional[str]

Error info compression algorithm. Used along with error_info_path.

None

__del__()

Cleanup.

__fingerprint(t, v, stack)

Calculate the error fingerprint.

Calculate error fingerprint for given exception and the stack. Fingerprint is stable for repeating conditions.

Parameters:

Name Type Description Default
t Type[BaseException]

Exception type.

required
v BaseException

Exception instance:

required
stack List[FrameInfo]

Current stack.

required

Returns:

Type Description
UUID

Error fingerprint as UUID.

__must_die(t, v, tb)

Check if the error is fatal and the process must die.

Process fail-fast sequence and return True if the process must die quickly.

__process(t, v, tb=None)

Process given exception context.

Called either from .process() or as sys.excepthook for unhandled exceptions.

Parameters:

Name Type Description Default
t Type[BaseException]

Exception type.

required
v BaseException

Exception value.

required
tb Optional[TracebackType]

Traceback frame.

None

Raises:

Type Description
RuntimeError

If setup() is not called.

__run_middleware(err_info)

Process all the middleware.

Parameters:

Name Type Description Default
err_info ErrorInfo

Filled ErrorInfo structure

required

add_fail_fast(ff)

Add fail-fast handler to the end of the chain.

Parameters:

Name Type Description Default
ff BaseFailFast

BaseFailFast instance.

required

Raises:

Type Description
ValueError

If ff is not BaseFailFast instance.

add_middleware(mw)

Add middleware to the end of the chain.

Parameters:

Name Type Description Default
mw BaseMiddleware

BaseMiddleware instance

required

Raises:

Type Description
ValueError

If mw is not BaseMiddleware instance.

iter_fingerprint_parts(t, v, stack)

Iterate over the fingerprint parts.

Iterable to yield all fingerprint parts. May be overriden in subclasses.

Parameters:

Name Type Description Default
t Type[BaseException]

Exception type.

required
v BaseException

Exception instance:

required
stack List[FrameInfo]

Current stack.

required

Returns:

Type Description
Iterable[str]

Iterable of strings.

process()

Process current exception context in the fenced code block.

Example
from gufo.err import err

...
try:
    my_function()
except Exception:
    err.process()

setup(*, catch_all=False, root_module=None, name=DEFAULT_NAME, version=DEFAULT_VERSION, hash=DEFAULT_HASH, fail_fast=None, fail_fast_code=DEFAULT_EXIT_CODE, middleware=None, format='terse', error_info_path=None, error_info_compress=None)

Setup error handling singleton.

Must be called only once.

Parameters:

Name Type Description Default
catch_all bool

Install global system exception hook.

False
name str

Application or service name.

DEFAULT_NAME
version str

Application or service version.

DEFAULT_VERSION
root_module Optional[str]

Top-level application module/namespace for split stack fingerprinting. Topmost frame from the root or the nested modules will be considered in the error fingerprint.

None
hash str

Fingerprint hashing function name. Available functions are: sha256, sha3_512, blake2s, sha3_224, md5, sha384, sha3_256, shake_256, blake2b, sha224, shake_128, sha3_384, sha1, sha512. Refer to the Python's hashlib for details.

DEFAULT_HASH
fail_fast Optional[Iterable[BaseFailFast]]

Iterable of BaseFailFast instances for fail-fast detection. Process will terminate with fail_fast_code error code if any of instances in the chain will return True.

None
fail_fast_code int

System exit code on fail-fast termination.

DEFAULT_EXIT_CODE
middleware Optional[Iterable[BaseMiddleware]]

Iterable of BaseMiddleware instances for error processing middleware. Instances are evaluated in the order of appearance.

None
format Optional[str]

If not None install TracebackMiddleware for given output format.

'terse'
error_info_path Optional[str]

If not None install ErrorInfoMiddleware. error_info_path should point to a writable directories, in which the error info files to be written.

None
error_info_compress Optional[str]

Used only with error_info_path. Set error info compression method. One of:

  • None - do not compress
  • gz - GZip
  • bz2 - BZip2
  • xz - LZMA/xz
None

Returns:

Type Description
Err

Err instance.

Raises:

Type Description
RuntimeError

When called twice.

ValueError

On configuration parameters error.

ErrorInfo dataclass

Bases: object

Current execution frame information.

Parameters:

Name Type Description Default
name str

Application or service name, as set by setup()

required
version str

Application or service version, as set by setup()

required
fingerprint UUID

Error fingerprint.

required
stack List[FrameInfo]

List of FrameInfo. Current execution frame is first.

required
exception BaseException

Exception instance, if caught.

required
timestamp Optional[datetime]

Error timestamp.

None
root_module Optional[str]

Optional root module, as set by setup()

None

get_app_top_frame()

Get application's top stack frame.

Find top stack frame belonging to the application, if root_module is set, or return stack top otherwise.

Returns:

Type Description
Optional[FrameInfo]
Optional[FrameInfo]
  • None otherwise.

FrameInfo dataclass

Bases: object

Execution frame.

Parameters:

Name Type Description Default
name str

Current callable name.

required
source Optional[SourceInfo]

Optional SourceInfo procedure. May be missed on loader problems.

required
locals Dict[str, Any]

Dicts of local variables.

required
module Optional[str]

Python module name.

None

SourceInfo dataclass

Bases: object

Source context for frame.

Parameters:

Name Type Description Default
file_name str

Normalized file name.

required
first_line int

first line of source context.

required
current_line int

current execution line.

required
lines List[str]

List of lines, starting from first_line

required
pos Optional[CodePosition]

Optional exact code position for Python 3.11+

None

exc_traceback()

Cast type to sys.exc_info().

Extract and return top-level excecution frame from current exception context.

Returns:

Type Description
TracebackType

Top-level exception frame.

iter_frames(tb, context_lines=7)

Iterate over traceback frames.

Parameters:

Name Type Description Default
tb TracebackType

current execution frame.

required
context_lines int

Source code context to extract. Current line, up to context_lines below the current line, and up to context_lines above the current line will be extracted.

7

Returns:

Type Description
Iterable[FrameInfo]

Iterable of FrameInfo, starting from top of the

Iterable[FrameInfo]

stack (current code position).