Skip to content

Commit

Permalink
fix: handle internal error and return HTTP 500
Browse files Browse the repository at this point in the history
  • Loading branch information
raphael0202 committed Dec 4, 2023
1 parent c77f049 commit 4e5bdbc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
10 changes: 10 additions & 0 deletions robotoff/app/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down
16 changes: 16 additions & 0 deletions tests/integration/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from datetime import datetime

import pytest
import requests
from falcon import testing

from robotoff.app import events
Expand Down Expand Up @@ -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}}
Expand Down

0 comments on commit 4e5bdbc

Please sign in to comment.