diff --git a/umodbus/exceptions.py b/umodbus/exceptions.py index 85a9a56..0f6a1cd 100644 --- a/umodbus/exceptions.py +++ b/umodbus/exceptions.py @@ -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. diff --git a/umodbus/functions.py b/umodbus/functions.py index 4db3cec..ed465d2 100644 --- a/umodbus/functions.py +++ b/umodbus/functions.py @@ -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. @@ -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