• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

hardbyte / python-can / 16362801995

18 Jul 2025 05:17AM UTC coverage: 70.862% (+0.1%) from 70.763%
16362801995

Pull #1920

github

web-flow
Merge f9e8a3c29 into 958fc64ed
Pull Request #1920: add FD support to slcan according to CANable 2.0 impementation

6 of 45 new or added lines in 1 file covered. (13.33%)

838 existing lines in 35 files now uncovered.

7770 of 10965 relevant lines covered (70.86%)

13.53 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.0
/can/exceptions.py
1
"""
21✔
2
There are several specific :class:`Exception` classes to allow user
3
code to react to specific scenarios related to CAN buses::
4

5
    Exception (Python standard library)
6
     +-- ...
7
     +-- CanError (python-can)
8
         +-- CanInterfaceNotImplementedError
9
         +-- CanInitializationError
10
         +-- CanOperationError
11
         +-- CanTimeoutError
12

13
Keep in mind that some functions and methods may raise different exceptions.
14
For example, validating typical arguments and parameters might result in a
15
:class:`ValueError`. This should always be documented for the function at hand.
16
"""
17

18
from collections.abc import Generator
21✔
19
from contextlib import contextmanager
21✔
20
from typing import Optional
21✔
21

22

23
class CanError(Exception):
21✔
24
    """Base class for all CAN related exceptions.
21✔
25

26
    If specified, the error code is automatically appended to the message:
27

28
    .. testsetup:: canerror
29

30
        from can import CanError, CanOperationError
31

32
    .. doctest:: canerror
33

34
        >>> # With an error code (it also works with a specific error):
35
        >>> error = CanOperationError(message="Failed to do the thing", error_code=42)
36
        >>> str(error)
37
        'Failed to do the thing [Error Code 42]'
38
        >>>
39
        >>> # Missing the error code:
40
        >>> plain_error = CanError(message="Something went wrong ...")
41
        >>> str(plain_error)
42
        'Something went wrong ...'
43

44
    :param error_code:
45
        An optional error code to narrow down the cause of the fault
46

47
    :arg error_code:
48
        An optional error code to narrow down the cause of the fault
49
    """
50

51
    def __init__(
21✔
52
        self,
53
        message: str = "",
54
        error_code: Optional[int] = None,
55
    ) -> None:
56
        self.error_code = error_code
21✔
57
        super().__init__(
21✔
58
            message if error_code is None else f"{message} [Error Code {error_code}]"
59
        )
60

61

62
class CanInterfaceNotImplementedError(CanError, NotImplementedError):
21✔
63
    """Indicates that the interface is not supported on the current platform.
21✔
64

65
    Example scenarios:
66
      - No interface with that name exists
67
      - The interface is unsupported on the current operating system or interpreter
68
      - The driver could not be found or has the wrong version
69
    """
70

71

72
class CanInitializationError(CanError):
21✔
73
    """Indicates an error the occurred while initializing a :class:`can.BusABC`.
21✔
74

75
    If initialization fails due to a driver or platform missing/being unsupported,
76
    a :exc:`~can.exceptions.CanInterfaceNotImplementedError` is raised instead.
77
    If initialization fails due to a value being out of range, a :class:`ValueError`
78
    is raised.
79

80
    Example scenarios:
81
      - Try to open a non-existent device and/or channel
82
      - Try to use an invalid setting, which is ok by value, but not ok for the interface
83
      - The device or other resources are already used
84
    """
85

86

87
class CanOperationError(CanError):
21✔
88
    """Indicates an error while in operation.
21✔
89

90
    Example scenarios:
91
      - A call to a library function results in an unexpected return value
92
      - An invalid message was received
93
      - The driver rejected a message that was meant to be sent
94
      - Cyclic redundancy check (CRC) failed
95
      - A message remained unacknowledged
96
      - A buffer is full
97
    """
98

99

100
class CanTimeoutError(CanError, TimeoutError):
21✔
101
    """Indicates the timeout of an operation.
21✔
102

103
    Example scenarios:
104
      - Some message could not be sent after the timeout elapsed
105
      - No message was read within the given time
106
    """
107

108

109
@contextmanager
21✔
110
def error_check(
21✔
111
    error_message: Optional[str] = None,
112
    exception_type: type[CanError] = CanOperationError,
113
) -> Generator[None, None, None]:
114
    """Catches any exceptions and turns them into the new type while preserving the stack trace."""
115
    try:
21✔
116
        yield
21✔
117
    except Exception as error:  # pylint: disable=broad-except
21✔
118
        if error_message is None:
21✔
UNCOV
119
            raise exception_type(str(error)) from error
×
120
        else:
121
            raise exception_type(error_message) from error
21✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc