Skip to content

Commit

Permalink
fix: issues hugapi#911
Browse files Browse the repository at this point in the history
  • Loading branch information
panlq01 committed Dec 12, 2022
1 parent 8b5ac00 commit 27f3c67
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
7 changes: 5 additions & 2 deletions hug/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 50 additions & 0 deletions tests/test_exception_handler.py
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 27f3c67

Please sign in to comment.