Skip to content

feat(socketcan): name the channel when binding a socket fails - #2184

Open
ChuangMuLinze wants to merge 1 commit into
hardbyte:mainfrom
ChuangMuLinze:feat/socketcan-bind-error-context
Open

ChuangMuLinze wants to merge 1 commit into
hardbyte:mainfrom
ChuangMuLinze:feat/socketcan-bind-error-context

Conversation

@ChuangMuLinze

Copy link
Copy Markdown

Closes #2104

Description of the Change

bind_socket() re-raised the OSError from socket.bind() unchanged. Client code that catches it therefore had no way to tell which bus failed when several were in use, unless debug logging was on.

The channel is now attached as a note on the original exception, and the failure is logged:

    try:
        sock.bind((channel,))
    except OSError as exc:
        exc.add_note(f"Failed to bind SocketCAN socket to channel {channel!r}.")
        log.exception("Error binding SocketCAN socket to channel %r", channel)
        raise

A traceback now ends with:

OSError: [Errno 19] No such device
Failed to bind SocketCAN socket to channel 'vcan42'.

I used add_note() rather than re-raising a new exception so that except OSError keeps working and errno/strerror are preserved — only the context is added. add_note() is available on every version python-can supports (requires-python = ">=3.11").

How I Tested It

Two tests in test/test_socketcan_helpers.py, both driven by a mocked socket so they need no CAN hardware:

  • test_bind_socket_adds_context_to_oserror — the raised OSError carries a note naming the channel. Fails on main (expected the channel in []), passes with the change.
  • test_bind_socket_keeps_original_error — the exception stays an OSError with errno == 19 and the original strerror.
$ python -m pytest test/test_socketcan.py test/test_socketcan_helpers.py -q
17 passed, 5 skipped, 7 subtests passed

black --check and ruff report nothing new on the touched files.

Scope

I kept this to the one call site the issue points at. The issue also suggests auditing other places that raise naked OSErrors without context — I'd rather do that separately, so this stays reviewable in one pass.

bind_socket() re-raised the OSError from socket.bind() unchanged, so client
code that catches it had no way to tell which bus failed when several were in
use. Add the channel as a note on the exception, following the pattern used
by candump for the same failure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make socket binding exceptions more debugable

1 participant