From 4e5bdbc0c1a1c3b87e19a952efe90eee8f25f208 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Bournhonesque?= Date: Mon, 4 Dec 2023 18:41:15 +0100 Subject: [PATCH] fix: handle internal error and return HTTP 500 --- robotoff/app/api.py | 10 ++++++++++ tests/integration/test_api.py | 16 ++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/robotoff/app/api.py b/robotoff/app/api.py index 22feba3aa5..7a993d0ad5 100644 --- a/robotoff/app/api.py +++ b/robotoff/app/api.py @@ -1800,6 +1800,14 @@ def on_get(self, req: falcon.Request, resp: falcon.Response): resp.status = falcon.HTTP_200 +def custom_handle_uncaught_exception( + req: falcon.Request, resp: falcon.Response, ex: Exception, params +): + """Handle uncaught exceptions and log them. Return a 500 error to the + client.""" + raise falcon.HTTPInternalServerError(description=str(ex)) + + cors = CORS( allow_all_origins=True, allow_all_headers=True, @@ -1818,6 +1826,8 @@ def on_get(self, req: falcon.Request, resp: falcon.Response): } api.resp_options.media_handlers.update(extra_handlers) +# Handle uncaught exceptions +api.add_error_handler(Exception, custom_handle_uncaught_exception) # Parse form parameters api.req_options.auto_parse_form_urlencoded = True diff --git a/tests/integration/test_api.py b/tests/integration/test_api.py index 66a351addc..9e1558c84e 100644 --- a/tests/integration/test_api.py +++ b/tests/integration/test_api.py @@ -3,6 +3,7 @@ from datetime import datetime import pytest +import requests from falcon import testing from robotoff.app import events @@ -1252,6 +1253,21 @@ def test_predict_lang(client, mocker): assert result.json == {"predictions": expected_predictions} +def test_predict_lang_http_error(client, mocker): + mocker.patch( + "robotoff.app.api.predict_lang", + side_effect=requests.exceptions.ConnectionError(), + ) + result = client.simulate_get( + "/api/v1/predict/lang", params={"text": "hello", "k": 2} + ) + assert result.status_code == 500 + assert result.json == { + "description": "Internal Server Error", + "title": "500 Internal Server Error", + } + + def test_predict_product_language(client, peewee_db): barcode = "123456789" prediction_data_1 = {"count": {"en": 10, "fr": 5, "es": 3, "words": 18}}