spiff-arena/SpiffWorkflow/exceptions.py
burnettk d581ac9b22 Squashed 'SpiffWorkflow/' changes from bee868d38..96ad2a2b0
96ad2a2b0 Merge pull request #311 from sartography/feature/error-message-on-bad-child-task
3fb69038d Merge remote-tracking branch 'origin/main' into feature/error-message-on-bad-child-task
df703ebb8 Merge remote-tracking branch 'origin/feature/add_task_not_found_error'
d6e244bcf also raise TaskNotFoundException from bpmn workflow w/ burnettk
37d7ae679 Merge pull request #310 from sartography/feature/add_task_not_found_error
7f4d38ce2 give us a better error if for some reason a task does not exist
b98efbd20 added an exception for task not found w/ burnettk
e1add839d Merge pull request #308 from sartography/bugfix/execute-event-gateways-on-ready
964c0231a do not predict tasks when deserializing, add method to predict all unfinished tasks
114f87aa9 update event gateway
62454c99c Merge pull request #307 from sartography/feature/standardize-task-execution
a087d29ea update task_spec._run to return a boolean & misc cleanup
9864d753d reenable recursion test
1bb1246a0 rename methods & move ready_before tasks from run to ready
12ce08519 move event task execution to run
d51bb68eb cleanup predictions
5e05458a3 make all tasks execute when run rather than completed (except bpmn events)
273d7b325 create a run method for tasks
3c3345c85 Merge pull request #306 from sartography/feature/create-core-test-package
ed85547d7 hopefully fix CI job, also update some deprecated assertions
80d68c231 cleanup around finding tasks
ea5ffff41 create tests based on individual patterns
afe41fba1 move core tests into one package
c075d52bc remove locks from task spec -- they don't do anything
d78c7cc04 reorganize so that related methods are near each other
f162aac43 Merge pull request #305 from sartography/feature/remove-loop-reset
6cad29817 'fix' old serializer to remove loop resets -- or at least get the tests to pass
a95d2fc12 add serialization migration that removes loop resets
c076175c8 account for DST in timers
42b483054 Merge pull request #303 from sartography/bugfix/execute-tasks-on-ready
2bb08aae1 update script/service tasks to execute on ready
0bd23a0ab fix scripts in business rule tasks
13034aaf1 prevent loop reset tasks from being inserted
3fb80518d update join execution model

git-subtree-dir: SpiffWorkflow
git-subtree-split: 96ad2a2b060deb445c39374f065690023351de19
2023-04-07 11:46:14 -04:00

136 lines
5.0 KiB
Python

# -*- coding: utf-8 -*-
# Copyright (C) 2007 Samuel Abels
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA
import re
from SpiffWorkflow.util import levenshtein
class SpiffWorkflowException(Exception):
"""
Base class for all SpiffWorkflow-generated exceptions.
"""
def __init__(self, msg):
super().__init__(msg)
self.notes = []
def add_note(self, note):
"""add_note is a python 3.11 feature, this can be removed when we
stop supporting versions prior to 3.11"""
self.notes.append(note)
def __str__(self):
return super().__str__() + ". " + ". ".join(self.notes)
class WorkflowException(SpiffWorkflowException):
"""
Base class for all SpiffWorkflow-generated exceptions.
"""
def __init__(self, message, task_spec=None):
"""
Standard exception class.
:param task_spec: the task spec that threw the exception
:type task_spec: TaskSpec
:param error: a human-readable error message
:type error: string
"""
super().__init__(str(message))
# Points to the TaskSpec that generated the exception.
self.task_spec = task_spec
@staticmethod
def get_task_trace(task):
task_trace = [f"{task.task_spec.description} ({task.workflow.spec.file})"]
workflow = task.workflow
while workflow != workflow.outer_workflow:
caller = workflow.name
workflow = workflow.outer_workflow
task_trace.append(f"{workflow.spec.task_specs[caller].description} ({workflow.spec.file})")
return task_trace
@staticmethod
def did_you_mean_from_name_error(name_exception, options):
"""Returns a string along the lines of 'did you mean 'dog'? Given
a name_error, and a set of possible things that could have been called,
or an empty string if no valid suggestions come up. """
if isinstance(name_exception, NameError):
def_match = re.match("name '(.+)' is not defined", str(name_exception))
if def_match:
bad_variable = re.match("name '(.+)' is not defined",
str(name_exception)).group(1)
most_similar = levenshtein.most_similar(bad_variable,
options, 3)
error_msg = ""
if len(most_similar) == 1:
error_msg += f' Did you mean \'{most_similar[0]}\'?'
if len(most_similar) > 1:
error_msg += f' Did you mean one of \'{most_similar}\'?'
return error_msg
class WorkflowTaskException(WorkflowException):
"""WorkflowException that provides task_trace information."""
def __init__(self, error_msg, task=None, exception=None,
line_number=None, offset=None, error_line=None):
"""
Exception initialization.
:param task: the task that threw the exception
:type task: Task
:param error_msg: a human readable error message
:type error_msg: str
:param exception: an exception to wrap, if any
:type exception: Exception
"""
self.task = task
self.line_number = line_number
self.offset = offset
self.error_line = error_line
if exception:
self.error_type = exception.__class__.__name__
else:
self.error_type = "unknown"
super().__init__(error_msg, task_spec=task.task_spec)
if isinstance(exception, SyntaxError) and not line_number:
# Line number and offset can be recovered directly from syntax errors,
# otherwise they must be passed in.
self.line_number = exception.lineno
self.offset = exception.offset
elif isinstance(exception, NameError):
self.add_note(self.did_you_mean_from_name_error(exception, list(task.data.keys())))
# If encountered in a sub-workflow, this traces back up the stack,
# so we can tell how we got to this particular task, no matter how
# deeply nested in sub-workflows it is. Takes the form of:
# task-description (file-name)
self.task_trace = self.get_task_trace(task)
class StorageException(SpiffWorkflowException):
pass
class TaskNotFoundException(WorkflowException):
pass