Skip to content

Commit

Permalink
improve expection handling with raise_errors=True, fixing GH133
Browse files Browse the repository at this point in the history
  • Loading branch information
newville committed Sep 22, 2024
1 parent 3c55649 commit 84ed2f3
Showing 1 changed file with 16 additions and 17 deletions.
33 changes: 16 additions & 17 deletions asteval/asteval.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,14 +217,13 @@ def unimplemented(self, node):
msg = f"{node.__class__.__name__} not supported"
self.raise_exception(node, exc=NotImplementedError, msg=msg)

def raise_exception(self, node, exc=None, msg='', expr=None,
lineno=None):
def raise_exception(self, node, exc=None, msg='', expr=None, lineno=None):
"""Add an exception."""
if expr is None:
expr = self.expr
if expr is not None:
self.expr = expr
msg = str(msg)
err = ExceptionHolder(node, exc=exc, msg=msg, expr=expr, lineno=lineno)

err = ExceptionHolder(node, exc=exc, msg=msg, expr=self.expr, lineno=lineno)
self._interrupt = ast.Raise()
self.error.append(err)
if self.error_msg is None:
Expand Down Expand Up @@ -285,7 +284,7 @@ def run(self, node, expr=None, lineno=None, with_raise=True):
try:
handler = self.node_handlers[node.__class__.__name__.lower()]
except KeyError:
self.raise_exception(None, exc=NotImplementedError, expr=expr)
self.raise_exception(None, exc=NotImplementedError, expr=self.expr)

# run the handler: this will likely generate
# recursive calls into this run method.
Expand All @@ -295,9 +294,8 @@ def run(self, node, expr=None, lineno=None, with_raise=True):
ret = list(ret)
return ret
except:
if with_raise:
self.raise_exception(node, expr=expr)
raise
if with_raise and self.expr is not None:
self.raise_exception(node, expr=self.expr)

# avoid too many repeated error messages (yes, this needs to be "2")
if len(self.error) > 2:
Expand Down Expand Up @@ -327,22 +325,23 @@ def eval(self, expr, lineno=0, show_errors=True, raise_errors=False):
lerr = self.error[-1]
errmsg = lerr.get_error()[1]
if raise_errors:
raise lerr.exc(errmsg) from exc
raise lerr.exc(errmsg)
if show_errors:
print(errmsg, file=self.err_writer)
return None
else:
node = expr
try:
return self.run(node, expr=expr, lineno=lineno, with_raise=raise_errors)
except:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = self.error[-1].get_error()[1]
if raise_errors:
raise self.error[-1].exc(errmsg) from exc
if show_errors:
except Exception:
if show_errors and not raise_errors:
errmsg = exc_info()[1]
if len(self.error) > 0:
errmsg = self.error[-1].get_error()[1]
print(errmsg, file=self.err_writer)
if raise_errors and len(self.error) > 0:
err = self.error[-1]
raise err.exc(err.get_error()[1])
return None

@staticmethod
Expand Down

0 comments on commit 84ed2f3

Please sign in to comment.