Skip to content

Commit 46780da

Browse files
authored
fix: don't exit on reload if there is a syntax error (#214)
* fix: don't exit on reload if there is a syntax error (#213) * style: reformat using black * test: robustness to syntax error in debug mode startup
1 parent 3190715 commit 46780da

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/functions_framework/__init__.py

+21-2
Original file line numberDiff line numberDiff line change
@@ -357,11 +357,30 @@ def handle_none(rv):
357357

358358
# Execute the module, within the application context
359359
with _app.app_context():
360-
spec.loader.exec_module(source_module)
360+
try:
361+
spec.loader.exec_module(source_module)
362+
function = _function_registry.get_user_function(
363+
source, source_module, target
364+
)
365+
except Exception as e:
366+
if werkzeug.serving.is_running_from_reloader():
367+
# When reloading, print out the error immediately, but raise
368+
# it later so the debugger or server can handle it.
369+
import traceback
370+
371+
traceback.print_exc()
372+
err = e
373+
374+
def function(*_args, **_kwargs):
375+
raise err from None
376+
377+
else:
378+
# When not reloading, raise the error immediately so the
379+
# command fails.
380+
raise e from None
361381

362382
# Get the configured function signature type
363383
signature_type = _function_registry.get_func_signature_type(target, signature_type)
364-
function = _function_registry.get_user_function(source, source_module, target)
365384

366385
_configure_app(_app, function, signature_type)
367386

tests/test_functions.py

+13
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,19 @@ def test_invalid_function_definition_function_syntax_error():
323323
)
324324

325325

326+
def test_invalid_function_definition_function_syntax_robustness_with_debug(monkeypatch):
327+
monkeypatch.setattr(
328+
functions_framework.werkzeug.serving, "is_running_from_reloader", lambda: True
329+
)
330+
source = TEST_FUNCTIONS_DIR / "background_load_error" / "main.py"
331+
target = "function"
332+
333+
client = create_app(target, source).test_client()
334+
335+
resp = client.get("/")
336+
assert resp.status_code == 500
337+
338+
326339
def test_invalid_function_definition_missing_dependency():
327340
source = TEST_FUNCTIONS_DIR / "background_missing_dependency" / "main.py"
328341
target = "function"

0 commit comments

Comments
 (0)