From 66fb4c28224ba84e8682c85cf363c7e4193dcca8 Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Mon, 19 Mar 2012 09:31:28 -0400 Subject: [PATCH] Add attributes to PyComediError to make intelligent error handling easier. --- pycomedi/__init__.py | 13 ++++++++++++- pycomedi/_error.pyx | 19 ++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/pycomedi/__init__.py b/pycomedi/__init__.py index bec6914..673ef88 100644 --- a/pycomedi/__init__.py +++ b/pycomedi/__init__.py @@ -36,4 +36,15 @@ del h, f class PyComediError (Exception): "Error in pycomedi" - pass + def __init__(self, function_name=None, ret=None, comedi_msg=None, + error_msg=None): + self.function_name = function_name + self.ret = ret + self.comedi_msg = comedi_msg + self.error_msg = error_msg + if error_msg: + msg = '{} ({}): {} ({})'.format( + function_name, error_msg, comedi_msg, ret) + else: + msg = '{}: {} ({})'.format(function_name, comedi_msg, ret) + super(PyComediError, self).__init__(msg) diff --git a/pycomedi/_error.pyx b/pycomedi/_error.pyx index 6a2245c..4cd4cea 100644 --- a/pycomedi/_error.pyx +++ b/pycomedi/_error.pyx @@ -24,9 +24,10 @@ from pycomedi import PyComediError as _PyComediError cimport _comedilib_h -def raise_error(function_name='', ret=None, error_msg=None): +def raise_error(function_name=None, ret=None, error_msg=None): """Report an error while executing a comedilib function + >>> from pycomedi import PyComediError >>> raise_error(function_name='myfn', ret=-1) Traceback (most recent call last): ... @@ -35,15 +36,19 @@ def raise_error(function_name='', ret=None, error_msg=None): Traceback (most recent call last): ... PyComediError: myfn (some error): Success (-1) + >>> try: + ... raise_error(function_name='myfn', ret=-1) + ... except PyComediError, e: + ... print(e.function_name) + ... print(e.ret) + myfn + -1 """ errno = _comedilib_h.comedi_errno() comedi_msg = _comedilib_h.comedi_strerror(errno) - #_comedilib_h.comedi_perror(function_name) - if error_msg: - msg = '%s (%s): %s (%s)' % (function_name, error_msg, comedi_msg, ret) - else: - msg = '%s: %s (%s)' % (function_name, comedi_msg, ret) - raise _PyComediError(msg) + raise _PyComediError( + function_name=function_name, ret=ret, comedi_msg=comedi_msg, + error_msg=error_msg) def _comedi_getter(name, is_invalid): -- 2.26.2