Skip to content

Commit 04f21b2

Browse files
authored
Merge pull request #76 from nitrictech/runtime-resource-errors
Provide more informative error when resources are declared at runtime
2 parents adcfbe2 + 433c616 commit 04f21b2

2 files changed

Lines changed: 26 additions & 10 deletions

File tree

nitric/api/exception.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ class UnknownException(NitricServiceException):
141141

142142
pass
143143

144+
class NitricResourceException(Exception):
145+
pass
144146

145147
def exception_from_grpc_error(error: GRPCError):
146148
"""Translate a gRPC error to a nitric api exception."""

nitric/resources/base.py

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,16 @@
2525
from typing import TypeVar, Type, Union, List
2626

2727
from grpclib import GRPCError
28-
from nitricapi.nitric.resource.v1 import Action, PolicyResource, Resource, ResourceType, ResourceDeclareRequest, \
29-
ResourceServiceStub
30-
31-
from nitric.api.exception import exception_from_grpc_error
28+
from nitricapi.nitric.resource.v1 import (
29+
Action,
30+
PolicyResource,
31+
Resource,
32+
ResourceType,
33+
ResourceDeclareRequest,
34+
ResourceServiceStub,
35+
)
36+
37+
from nitric.api.exception import exception_from_grpc_error, NitricResourceException
3238
from nitric.utils import new_default_channel
3339

3440
T = TypeVar("T", bound="BaseResource")
@@ -69,7 +75,7 @@ def make(cls: Type[T], name: str) -> T:
6975

7076

7177
class SecureResource(BaseResource):
72-
"""A secure base resource class"""
78+
"""A secure base resource class."""
7379

7480
@abstractmethod
7581
def _to_resource(self) -> Resource:
@@ -90,12 +96,20 @@ async def _register_policy_async(self, *args: str):
9096
)
9197
try:
9298
await self._resources_stub.declare(
93-
resource_declare_request=ResourceDeclareRequest(resource=Resource(type=ResourceType.Policy),
94-
policy=policy))
99+
resource_declare_request=ResourceDeclareRequest(
100+
resource=Resource(type=ResourceType.Policy), policy=policy
101+
)
102+
)
95103
except GRPCError as grpc_err:
96104
raise exception_from_grpc_error(grpc_err)
97105

98106
def _register_policy(self, *args: str):
99-
loop = asyncio.get_event_loop()
100-
loop.run_until_complete(self._register_policy_async(*args))
101-
107+
try:
108+
loop = asyncio.get_event_loop()
109+
loop.run_until_complete(self._register_policy_async(*args))
110+
except RuntimeError:
111+
# TODO: Check nitric runtime ENV variable
112+
raise NitricResourceException(
113+
"Nitric resources cannot be declared at runtime e.g. within the scope of a function. \
114+
Move resource declarations to the top level of scripts so that they can be safely provisioned"
115+
)

0 commit comments

Comments
 (0)