From 27f3c67909b3d18630d72edc63ec62688a60e390 Mon Sep 17 00:00:00 2001 From: panlq01 Date: Mon, 12 Dec 2022 14:10:26 +0800 Subject: [PATCH] fix: issues https://github.com/hugapi/hug/issues/911 --- hug/interface.py | 7 +++-- tests/test_exception_handler.py | 50 +++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 tests/test_exception_handler.py diff --git a/hug/interface.py b/hug/interface.py index fe9f8f1c..43cc69b4 100644 --- a/hug/interface.py +++ b/hug/interface.py @@ -932,8 +932,11 @@ def __call__(self, request, response, api_version=None, **kwargs): )[::-1]: if isinstance(exception, match_exception_type): for potential_handler in exception_handlers: - if not isinstance(exception, potential_handler.exclude): - handler = potential_handler + if hasattr(potential_handler, "exclude") and isinstance(exception, potential_handler.exclude): + continue + + handler = potential_handler + break if not handler: raise exception diff --git a/tests/test_exception_handler.py b/tests/test_exception_handler.py new file mode 100644 index 00000000..653d5d38 --- /dev/null +++ b/tests/test_exception_handler.py @@ -0,0 +1,50 @@ +import hug +import time + +base_error_message = "500 Internal Server Error" +friendly_error_message = "Friendly error message" + + +class BaseError(Exception): + code = 500 + message = base_error_message + + def __init__(self): + ... + + def __str__(self): + return self.message + + +class FriendlyError(BaseError): + message = friendly_error_message + + +api = hug.API(__name__) + + +# @hug.exception(UserError, api=api) +def handler_friendly_error(request, response, exception): + # do something + response.status = hug.falcon.HTTP_200 + data = dict(data=None, msg=exception.message, timestamp=time.time(), code=exception.code) + response.body = hug.output_format.json(data) + + +def test_handler_direct_exception(): + @hug.object.urls("/test", requires=()) + class MyClass(object): + @hug.object.get() + def test(self): + raise FriendlyError() + + api.http.add_exception_handler(FriendlyError, handler_friendly_error) + assert hug.test.get(api, "/test").data.get("msg", "") == friendly_error_message + + # fix issues: https://github.com/hugapi/hug/issues/911 + api.http.add_exception_handler(BaseError, handler_friendly_error) + assert hug.test.get(api, "/test").data.get("msg", "") == friendly_error_message + + +if __name__ == "__main__": + test_handler_direct_exception() \ No newline at end of file