コンテンツにスキップ

Errors API

Purpose

This module handles error handling and exception management in RDEToolKit. It provides functionality for custom exception classes, error message management, exception capture and processing.

Key Features

Exception Management

  • Exception capture and appropriate handling
  • Simplified traceback display
  • Dedicated handling for structured errors

Error Handling

  • Standardization of error messages
  • Creation of job error log files
  • Generic error processing functionality

src.rdetoolkit.errors.catch_exception_with_message(*, error_message=None, error_code=None, eobj=None, verbose=False)

A decorator that catches exceptions and re-raises a StructuredError with a customized message and error code.

This decorator catches exceptions thrown within the decorated function. If a StructuredError is raised, it re-raises it with the specified error message, error code, and optional additional error object. For other exceptions, it re-raises them as standard Exceptions. The verbosity level of the error message can be controlled via the verbose parameter.

引数:

名前 タイプ デスクリプション デフォルト
error_message Optional[str]

Customized message to be used in case of an error. Defaults to None.

None
error_code Optional[int]

Error code to be used in case of an error. Defaults to None.

None
eobj Optional[Any]

Additional object to include in the error. Defaults to None.

None
verbose bool

If set to True, provides detailed error messages. Defaults to False.

False

戻り値:

名前 タイプ デスクリプション
Callable Callable

A function decorator that provides customized error handling on exception occurrence.


src.rdetoolkit.errors.format_simplified_traceback(tb_list)

Formats a simplified version of the traceback information.

This function takes a list of traceback frame summaries and constructs a formatted string representing the call stack. The formatted string includes indentation and node characters to indicate the call path, highlighting the file, line number, and function name. The final line of the traceback is marked with a fire emoji.

引数:

名前 タイプ デスクリプション デフォルト
tb_list list[FrameSummary]

A list of traceback frame summaries to format.

必須

戻り値:

名前 タイプ デスクリプション
str str

A formatted string representing the simplified traceback information.


src.rdetoolkit.errors.handle_exception(e, error_message=None, error_code=None, eobj=None, verbose=False, config=None)

Handles exceptions and formats them into a StructuredError with optional custom message, error code, and additional object.

This function captures the exception type and traceback, then formats a simplified version of the traceback. It constructs a custom error message, optionally including the full original traceback if verbose mode is enabled. The function returns a StructuredError containing the error message, error code, optional additional object, and simplified traceback information.

引数:

名前 タイプ デスクリプション デフォルト
e Exception

The exception to handle.

必須
error_message Optional[str]

Customized message to be used in case of an error. Defaults to the exception message.

None
error_code Optional[int]

Error code to be used in case of an error. Defaults to 1.

None
eobj Optional[Any]

Additional object to include in the error. Defaults to None.

None
verbose bool

If set to True, includes the original traceback in the error message. Defaults to False.

False
config Config | None

Optional configuration object whose traceback attribute (TracebackSettings) determines how traceback text is produced when e.traceback_info is missing. If None, traceback settings are resolved from environment variables (fallback behavior).

None

戻り値:

名前 タイプ デスクリプション
StructuredError StructuredError

A structured error object containing the error message, error code, additional object,

StructuredError

and simplified traceback information.


src.rdetoolkit.errors.handle_and_exit_on_structured_error(e, logger, config=None)

Catch StructuredError and write to log file.

引数:

名前 タイプ デスクリプション デフォルト
e StructuredError

StructuredError instance

必須
logger Logger

Logger instance

必須
config Config | None

Optional configuration object whose traceback attribute (TracebackSettings) determines how traceback text is produced when e.traceback_info is missing. If None, traceback settings are resolved from environment variables (fallback behavior)

None

src.rdetoolkit.errors.handle_generic_error(e, logger, config=None)

Catch a generic (non-StructuredError) exception, emit a formatted traceback, log it, and exit.

This helper
  1. Formats the exception into a structured traceback (compact or python style depending on settings).
  2. Writes the formatted traceback to stderr.
  3. Writes a generic job error file with a fixed error code (999) to assist external supervisors.
  4. Logs the exception (including stack trace) via the provided logger.
  5. Exits the process with status code 1.

引数:

名前 タイプ デスクリプション デフォルト
e Exception

The caught exception instance.

必須
logger Logger

Logger used to record the exception (logger.exception is invoked so a stack trace is included).

必須
config Config | None

Optional configuration object. If provided and it contains traceback settings, those settings control whether a compact traceback, a standard Python traceback, or both are generated. If omitted, traceback settings are resolved from the environment (see get_traceback_settings_from_env).

None
Side Effects
  • Writes structured traceback text to stderr.
  • Creates/overwrites an error marker file via write_job_errorlog_file (default filename: job.failed) with code=999.
  • Emits an ERROR-level log entry with stack trace.
  • Terminates the interpreter with sys.exit(1).

戻り値:

タイプ デスクリプション
None

None. (The function does not return; it terminates the process.)


src.rdetoolkit.errors.write_job_errorlog_file(code, message, *, filename='job.failed')

Write the error log to a file.

This function writes the given error code and message to a specified file. The file will be saved in a directory determined by StorageDir.get_datadir(False).

引数:

名前 タイプ デスクリプション デフォルト
code int

The error code to be written to the log file.

必須
message str

The error message to be written to the log file.

必須
filename str

The name of the file to which the error log will be written. Defaults to "job.failed".

'job.failed'
Example
1
write_job_errorlog_file(404, 'Not Found', filename='error.log')

Practical Usage

Using Exception Capture Decorator

exception_decorator.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from rdetoolkit.errors import catch_exception_with_message
from pathlib import Path

@catch_exception_with_message("Error occurred during data processing")
def process_data(data_file):
    """Data processing function (with error handling)"""
    if not data_file.exists():
        raise FileNotFoundError(f"File not found: {data_file}")

    # Data processing simulation
    with open(data_file, 'r') as f:
        content = f.read()
        if not content:
            raise ValueError("File is empty")

    return {"status": "success", "size": len(content)}

# Usage example
try:
    result = process_data(Path("data/sample.txt"))
    print(f"Processing result: {result}")
except Exception as e:
    print(f"Error: {e}")

Using Simplified Traceback

simplified_traceback.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from rdetoolkit.errors import format_simplified_traceback
import traceback

def problematic_function():
    """Problematic function"""
    raise ValueError("Some error occurred")

def calling_function():
    """Calling function"""
    problematic_function()

try:
    calling_function()
except Exception as e:
    # Standard traceback
    print("=== Standard Traceback ===")
    traceback.print_exc()

    # Simplified traceback
    print("\n=== Simplified Traceback ===")
    simplified_tb = format_simplified_traceback()
    print(simplified_tb)

Structured Error Handling

structured_error_handling.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from rdetoolkit.errors import handle_and_exit_on_structured_error, handle_exception
from rdetoolkit.exceptions import StructuredError

def risky_operation():
    """Risky operation"""
    # Raise structured error
    raise StructuredError("Error occurred in structured processing")

# Dedicated handling for structured errors
try:
    risky_operation()
except StructuredError as e:
    handle_and_exit_on_structured_error(e)
except Exception as e:
    handle_exception(e, "Unexpected error occurred")

Creating Error Log Files

error_logging.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from rdetoolkit.errors import write_job_errorlog_file, handle_generic_error
from pathlib import Path
import traceback

def run_job_with_error_logging(job_id: str):
    """Job execution with error logging"""

    try:
        # Execute job (may cause errors)
        print(f"Starting job {job_id}")

        # Intentionally cause error
        if job_id == "error_job":
            raise RuntimeError("Error occurred during job execution")

        print(f"Job {job_id} completed successfully")
        return {"status": "success", "job_id": job_id}

    except Exception as e:
        # Create error log file
        error_log_path = Path(f"logs/job_{job_id}_error.log")
        error_log_path.parent.mkdir(parents=True, exist_ok=True)

        write_job_errorlog_file(str(error_log_path), str(e), traceback.format_exc())

        # Generic error handling
        handle_generic_error(e, f"Error occurred in job {job_id}")

        return {"status": "error", "job_id": job_id, "error_log": str(error_log_path)}

# Usage example
jobs = ["normal_job", "error_job", "another_job"]

for job in jobs:
    print(f"\n--- Executing {job} ---")
    result = run_job_with_error_logging(job)
    print(f"Result: {result}")

Comprehensive Error Handling System

comprehensive_error_handling.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from rdetoolkit.errors import (
    catch_exception_with_message, 
    handle_exception, 
    format_simplified_traceback,
    write_job_errorlog_file
)
from pathlib import Path
import logging

class ErrorHandlingSystem:
    """Comprehensive error handling system"""

    def __init__(self, log_dir: Path):
        self.log_dir = log_dir
        self.log_dir.mkdir(parents=True, exist_ok=True)

        # Configure logger
        self.logger = logging.getLogger("error_system")
        self.logger.setLevel(logging.INFO)

        # Add file handler
        handler = logging.FileHandler(self.log_dir / "system.log")
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    @catch_exception_with_message("Error occurred during system processing")
    def safe_execute(self, func, *args, **kwargs):
        """Safe function execution"""
        try:
            self.logger.info(f"Starting execution of function {func.__name__}")
            result = func(*args, **kwargs)
            self.logger.info(f"Function {func.__name__} completed successfully")
            return result
        except Exception as e:
            # Detailed error logging
            error_log_path = self.log_dir / f"error_{func.__name__}.log"
            simplified_tb = format_simplified_traceback()
            write_job_errorlog_file(str(error_log_path), str(e), simplified_tb)

            # Error handling
            handle_exception(e, f"Error occurred in function {func.__name__}")

            return {"status": "error", "function": func.__name__, "error": str(e)}

# Usage example
def sample_function(value):
    """Sample function"""
    if value < 0:
        raise ValueError("Negative values are not allowed")
    return value * 2

def another_function(data):
    """Another sample function"""
    if not data:
        raise RuntimeError("Data is empty")
    return len(data)

# Use error handling system
error_system = ErrorHandlingSystem(Path("logs/error_system"))

# Normal case
result1 = error_system.safe_execute(sample_function, 5)
print(f"Result 1: {result1}")

# Error case
result2 = error_system.safe_execute(sample_function, -1)
print(f"Result 2: {result2}")

result3 = error_system.safe_execute(another_function, [])
print(f"Result 3: {result3}")