Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: issues https://github.com/hugapi/hug/issues/911 #913

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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()