Skip to content

Commit

Permalink
converted some more of the exceptions to rasa exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
tmbo committed Oct 19, 2020
1 parent 6d2aa45 commit 76c4588
Show file tree
Hide file tree
Showing 12 changed files with 60 additions and 68 deletions.
16 changes: 7 additions & 9 deletions rasa/core/actions/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,15 +595,14 @@ async def run(
) -> List[Event]:
json_body = self._action_call_format(tracker, domain)
if not self.action_endpoint:
logger.error(
f"The model predicted the custom action '{self.name()}', "
f"but you didn't configure an endpoint to "
f"run this custom action. Please take a look at "
raise RasaException(
f"Failed to execute custom action '{self.name()}' "
f"because no endpoint is configured to run this "
f"custom action. Please take a look at "
f"the docs and set an endpoint configuration via the "
f"--endpoints flag. "
f"{DOCS_BASE_URL}/custom-actions"
)
raise Exception("Failed to execute custom action.")

try:
logger.debug(
Expand Down Expand Up @@ -633,30 +632,29 @@ async def run(
logger.error(exception.message)
raise exception
else:
raise Exception("Failed to execute custom action.") from e
raise RasaException("Failed to execute custom action.") from e

except aiohttp.ClientConnectionError as e:
logger.error(
"Failed to run custom action '{}'. Couldn't connect "
"to the server at '{}'. Is the server running? "
"Error: {}".format(self.name(), self.action_endpoint.url, e)
)
raise Exception("Failed to execute custom action.")
raise RasaException("Failed to execute custom action.")

except aiohttp.ClientError as e:
# not all errors have a status attribute, but
# helpful to log if they got it

# noinspection PyUnresolvedReferences
status = getattr(e, "status", None)
logger.error(
raise RasaException(
"Failed to run custom action '{}'. Action server "
"responded with a non 200 status code of {}. "
"Make sure your action server properly runs actions "
"and returns a 200 once the action is executed. "
"Error: {}".format(self.name(), status, e)
)
raise Exception("Failed to execute custom action.")

def name(self) -> Text:
return self._name
Expand Down
50 changes: 18 additions & 32 deletions rasa/core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
DEFAULT_DOMAIN_PATH,
DEFAULT_CORE_SUBDIRECTORY_NAME,
)
from rasa.shared.exceptions import InvalidParameterException, RasaException
from rasa.shared.nlu.interpreter import NaturalLanguageInterpreter, RegexInterpreter
from rasa.core.lock_store import InMemoryLockStore, LockStore
from rasa.core.nlg import NaturalLanguageGenerator
Expand Down Expand Up @@ -419,13 +420,15 @@ def load(
raise ModelNotFound(f"No file or directory at '{model_path}'.")
if os.path.isfile(model_path):
model_path = get_model(str(model_path))
except ModelNotFound:
raise ValueError(
"You are trying to load a MODEL from '{}', which is not possible. \n"
"The model path should be a 'tar.gz' file or a directory "
"containing the various model files in the sub-directories 'core' "
"and 'nlu'. \n\nIf you want to load training data instead of "
"a model, use `agent.load_data(...)` instead.".format(model_path)
except ModelNotFound as e:
raise ModelNotFound(
f"You are trying to load a model from '{os.path.abspath(model_path)}', "
f"which is not possible. \n"
f"The model path should be a 'tar.gz' file or a directory "
f"containing the various model files in the sub-directories "
f"'core' and 'nlu'. \n\n"
f"If you want to load training data instead of a model, use "
f"`agent.load_data(...)` instead. {e}"
)

core_model, nlu_model = get_model_subdirectories(model_path)
Expand Down Expand Up @@ -508,13 +511,6 @@ async def handle_message(
) -> Optional[List[Dict[Text, Any]]]:
"""Handle a single message."""

if not isinstance(message, UserMessage):
# DEPRECATION EXCEPTION - remove in 2.1
raise Exception(
"Passing a text to `agent.handle_message(...)` is "
"not supported anymore. Rather use `agent.handle_text(...)`."
)

def noop(_: Any) -> None:
logger.info("Ignoring message as there is no agent to handle it.")

Expand Down Expand Up @@ -717,16 +713,6 @@ def train(
if not self.is_core_ready():
raise AgentNotReady("Can't train without a policy ensemble.")

if isinstance(training_trackers, str):
# the user most likely passed in a file name to load training
# data from
raise Exception(
"Passing a file name to `agent.train(...)` is "
"not supported anymore. Rather load the data with "
"`data = agent.load_data(file_name)` and pass it "
"to `agent.train(data)`."
)

logger.debug(f"Agent trainer got kwargs: {kwargs}")

self.policy_ensemble.train(
Expand Down Expand Up @@ -849,10 +835,10 @@ def _create_domain(domain: Union[Domain, Text, None]) -> Domain:
elif domain is None:
return Domain.empty()
else:
raise ValueError(
"Invalid param `domain`. Expected a path to a domain "
"specification or a domain instance. But got "
"type '{}' with value '{}'".format(type(domain), domain)
raise InvalidParameterException(
f"Invalid param `domain`. Expected a path to a domain "
f"specification or a domain instance. But got "
f"type '{type(domain)}' with value '{domain}'."
)

@staticmethod
Expand Down Expand Up @@ -886,10 +872,10 @@ def _create_ensemble(
return policies
else:
passed_type = type(policies).__name__
raise ValueError(
"Invalid param `policies`. Passed object is "
"of type '{}', but should be policy, an array of "
"policies, or a policy ensemble.".format(passed_type)
raise InvalidParameterException(
f"Invalid param `policies`. Passed object is "
f"of type '{passed_type}', but should be policy, an array of "
f"policies, or a policy ensemble."
)

@staticmethod
Expand Down
3 changes: 2 additions & 1 deletion rasa/core/channels/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from rasa.cli import utils as cli_utils
from rasa.shared.constants import DOCS_BASE_URL, DEFAULT_SENDER_ID
from rasa.shared.exceptions import RasaException

try:
from urlparse import urljoin
Expand Down Expand Up @@ -117,7 +118,7 @@ def blueprint(

@classmethod
def raise_missing_credentials_exception(cls) -> NoReturn:
raise Exception(
raise RasaException(
f"To use the {cls.name()} input channel, you need to "
f"pass a credentials file using '--credentials'. "
f"The argument should be a file path pointing to "
Expand Down
8 changes: 4 additions & 4 deletions rasa/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
from typing import Optional, Text, List, Dict, Union, Tuple, Any, TYPE_CHECKING

from rasa.shared.exceptions import FileNotFoundException
import rasa.shared.utils.io
import rasa.shared.utils.cli
from rasa.core.constants import (
Expand Down Expand Up @@ -41,10 +42,9 @@ def load(config_file: Optional[Union[Text, Dict]]) -> List["Policy"]:
from rasa.core.policies.ensemble import PolicyEnsemble

if not config_file:
raise ValueError(
"You have to provide a valid path to a config file. "
"The file '{}' could not be found."
"".format(os.path.abspath(config_file))
raise FileNotFoundException(
f"The provided configuration file path does not seem to be valid. "
f"The file '{os.path.abspath(config_file)}' could not be found."
)

config_data = {}
Expand Down
3 changes: 2 additions & 1 deletion rasa/core/lock_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from async_generator import asynccontextmanager
from typing import Text, Union, Optional, AsyncGenerator

from rasa.shared.exceptions import RasaException
import rasa.shared.utils.common
from rasa.core.constants import DEFAULT_LOCK_LIFETIME
from rasa.core.lock import TicketLock
Expand All @@ -23,7 +24,7 @@ def _get_lock_lifetime() -> int:


# noinspection PyUnresolvedReferences
class LockError(Exception):
class LockError(RasaException):
"""Exception that is raised when a lock cannot be acquired.
Attributes:
Expand Down
17 changes: 8 additions & 9 deletions rasa/core/nlg/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from rasa.core.constants import DEFAULT_REQUEST_TIMEOUT
from rasa.core.nlg.generator import NaturalLanguageGenerator
from rasa.shared.core.trackers import DialogueStateTracker, EventVerbosity
from rasa.shared.exceptions import RasaException
from rasa.utils.endpoints import EndpointConfig

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -103,12 +104,11 @@ async def generate(
if self.validate_response(response):
return response
else:
raise Exception("NLG web endpoint returned an invalid response.")
raise RasaException("NLG web endpoint returned an invalid response.")

@staticmethod
def validate_response(content: Optional[Dict[Text, Any]]) -> bool:
"""Validate the NLG response. Raises exception on failure."""

from jsonschema import validate
from jsonschema import ValidationError

Expand All @@ -120,11 +120,10 @@ def validate_response(content: Optional[Dict[Text, Any]]) -> bool:
validate(content, nlg_response_format_spec())
return True
except ValidationError as e:
e.message += (
". Failed to validate NLG response from API, make sure your "
"response from the NLG endpoint is valid. "
"For more information about the format please consult the "
"`nlg_response_format_spec` function from this same module: "
"https://github.com/RasaHQ/rasa/blob/master/rasa/core/nlg/callback.py"
raise RasaException(
f"{e.message}. Failed to validate NLG response from API, make sure "
f"your response from the NLG endpoint is valid. "
f"For more information about the format please consult the "
f"`nlg_response_format_spec` function from this same module: "
f"https://github.com/RasaHQ/rasa/blob/master/rasa/core/nlg/callback.py"
)
raise e
10 changes: 5 additions & 5 deletions rasa/core/visualize.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,19 +23,19 @@ async def visualize(

try:
policies = config.load(config_path)
except ValueError as e:
except Exception as e:
print_error(
"Could not load config due to: '{}'. To specify a valid config file use "
"the '--config' argument.".format(e)
f"Could not load config due to: '{e}'. To specify a valid config file use "
f"the '--config' argument."
)
return

try:
agent = Agent(domain=domain_path, policies=policies)
except InvalidDomain as e:
print_error(
"Could not load domain due to: '{}'. To specify a valid domain path use "
"the '--domain' argument.".format(e)
f"Could not load domain due to: '{e}'. To specify a valid domain path use "
f"the '--domain' argument."
)
return

Expand Down
4 changes: 2 additions & 2 deletions rasa/nlu/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -787,7 +787,7 @@ def load_component(
self.__add_to_cache(component, cache_key)
return component
except MissingArgumentError as e: # pragma: no cover
raise Exception(
raise RasaException(
f"Failed to load component from file '{component_meta.get('file')}'. "
f"Error: {e}"
)
Expand Down Expand Up @@ -820,7 +820,7 @@ def create_component(
self.__add_to_cache(component, cache_key)
return component
except MissingArgumentError as e: # pragma: no cover
raise Exception(
raise RasaException(
f"Failed to create component '{component_config['name']}'. "
f"Error: {e}"
)
Expand Down
8 changes: 5 additions & 3 deletions rasa/nlu/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from typing import Any, Optional, Text
from pathlib import Path

from rasa.shared.exceptions import RasaException
import rasa.shared.utils.io


Expand Down Expand Up @@ -62,7 +63,8 @@ def remove_model(model_dir: Text) -> bool:
shutil.rmtree(model_dir)
return True
else:
raise ValueError(
"Cannot remove {}, it seems it is not a model "
"directory".format(model_dir)
raise RasaException(
f"Failed to remove {model_dir}, it seems it is not a model "
f"directory. E.g. a directory which contains sub directories "
f"is considered unsafe to remove."
)
4 changes: 4 additions & 0 deletions rasa/shared/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class RasaXTermsError(RasaException):
"""Error in case the user didn't accept the Rasa X terms."""


class InvalidParameterException(RasaException, ValueError):
"""Raised when an invalid parameter is used."""


class YamlException(RasaException):
"""Raised if there is an error reading yaml."""

Expand Down
2 changes: 1 addition & 1 deletion rasa/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,7 @@ def initialize_error_reporting() -> None:
],
send_default_pii=False, # activate PII filter
server_name=telemetry_id or "UNKNOWN",
ignore_errors=[KeyboardInterrupt, RasaException],
ignore_errors=[KeyboardInterrupt, RasaException, NotImplementedError],
in_app_include=["rasa"], # only submit errors in this package
with_locals=False, # don't submit local variables
release=f"rasa-{rasa.__version__}",
Expand Down
3 changes: 2 additions & 1 deletion tests/nlu/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import tempfile
import shutil

from rasa.shared.exceptions import RasaException
import rasa.shared.nlu.training_data.message
import rasa.shared.utils.io
import rasa.utils.io as io_utils
Expand Down Expand Up @@ -96,7 +97,7 @@ def test_remove_model_invalid(empty_model_dir):
test_file_path = os.path.join(empty_model_dir, test_file)
utils.write_to_file(test_file_path, test_content)

with pytest.raises(ValueError):
with pytest.raises(RasaException):
utils.remove_model(empty_model_dir)

os.remove(test_file_path)
Expand Down

0 comments on commit 76c4588

Please sign in to comment.