Skip to content

Convert unknown error codes to a useful exception class. #112

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions umodbus/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,16 @@ class ModbusError(Exception):
pass


class UndefinedModbusError(ModbusError):
"""Catch-all class for non-standard error codes."""

def __init__(self, error_code):
self.error_code = error_code

def __str__(self):
return 'Non-standard Modbus error code %#04x received.' % self.error_code


class IllegalFunctionError(ModbusError):
""" The function code received in the request is not an allowable action for
the server.
Expand Down
8 changes: 6 additions & 2 deletions umodbus/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
from umodbus import conf, log
from umodbus.exceptions import (error_code_to_exception_map,
IllegalDataValueError, IllegalFunctionError,
IllegalDataAddressError)
IllegalDataAddressError, UndefinedModbusError)
from umodbus.utils import memoize, get_function_code_from_request_pdu

# Function related to data access.
Expand Down Expand Up @@ -115,7 +115,11 @@ def pdu_to_function_code_or_raise_error(resp_pdu):

if function_code not in function_code_to_function_map.keys():
error_code = struct.unpack('>B', resp_pdu[1:2])[0]
raise error_code_to_exception_map[error_code]
try:
exception = error_code_to_exception_map[error_code]
raise exception
except KeyError as e:
raise UndefinedModbusError(e.args[0])

return function_code

Expand Down