From 8220feabaaff7bcc88bfdacc1303e6ae90350c36 Mon Sep 17 00:00:00 2001 From: Tim Holm Date: Tue, 22 Nov 2022 14:37:40 +1100 Subject: [PATCH] fix: Print readable error when cannot connect to a nitric instance. --- nitric/api/exception.py | 10 ++++++++++ nitric/application.py | 18 ++++++++++++++---- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/nitric/api/exception.py b/nitric/api/exception.py index 736d552..f0eb270 100644 --- a/nitric/api/exception.py +++ b/nitric/api/exception.py @@ -141,9 +141,19 @@ class UnknownException(NitricServiceException): pass + class NitricResourceException(Exception): + """Illegal nitric resource creation.""" + pass + +class NitricUnavailableException(Exception): + """Unable to connect to a nitric server.""" + + pass + + def exception_from_grpc_error(error: GRPCError): """Translate a gRPC error to a nitric api exception.""" return exception_from_grpc_code(error.status.value, error.message) diff --git a/nitric/application.py b/nitric/application.py index eb05844..617ea56 100644 --- a/nitric/application.py +++ b/nitric/application.py @@ -1,5 +1,6 @@ import asyncio from nitric.faas import FunctionServer +from nitric.api.exception import NitricUnavailableException # from nitric.resources.base import BaseResource from typing import Dict, List, Type, Any, TypeVar @@ -28,11 +29,16 @@ def _register_worker(cls, srv: FunctionServer): @classmethod def _create_resource(cls, resource: Type[BT], name: str, *args, **kwargs) -> BT: - resource_type = resource.__name__.lower() - if cls._cache.get(resource_type).get(name) is None: - cls._cache[resource_type][name] = resource.make(name, *args, **kwargs) + try: + resource_type = resource.__name__.lower() + if cls._cache.get(resource_type).get(name) is None: + cls._cache[resource_type][name] = resource.make(name, *args, **kwargs) - return cls._cache[resource_type][name] + return cls._cache[resource_type][name] + except ConnectionRefusedError: + raise NitricUnavailableException( + 'Unable to connect to a nitric server! If you\'re running locally make sure to run "nitric start"' + ) @classmethod def run(cls): @@ -50,3 +56,7 @@ def run(cls): loop.run_until_complete(asyncio.gather(*[wkr.start() for wkr in cls._workers])) except KeyboardInterrupt: print("\nexiting") + except ConnectionRefusedError: + raise NitricUnavailableException( + 'Unable to connect to a nitric server! If you\'re running locally make sure to run "nitric start"' + )