diff --git a/changelog.d/+convert-exceptions-to-messages.changed.md b/changelog.d/+convert-exceptions-to-messages.changed.md new file mode 100644 index 000000000..e6cda47ab --- /dev/null +++ b/changelog.d/+convert-exceptions-to-messages.changed.md @@ -0,0 +1 @@ +Htmx: Otherwise uncaught exceptions are caught, logged and converted to messages.error. diff --git a/src/argus/htmx/middleware.py b/src/argus/htmx/middleware.py index cec287c91..25892fbfd 100644 --- a/src/argus/htmx/middleware.py +++ b/src/argus/htmx/middleware.py @@ -1,3 +1,5 @@ +import logging + from django.conf import settings from django.contrib.auth.views import redirect_to_login from django.http import HttpResponse @@ -6,8 +8,11 @@ from django.utils.encoding import force_str from django_htmx.http import HttpResponseClientRedirect from django.contrib import messages + from .request import HtmxHttpRequest +LOG = logging.getLogger(__name__) + class LoginRequiredMiddleware: def __init__(self, get_response): @@ -61,6 +66,14 @@ class HtmxMessageMiddleware(MiddlewareMixin): TEMPLATE = "messages/_notification_messages_htmx_append.html" + def process_exception(self, request, exception): + error_msg = "500 Internal Server Error" + if str(exception): + error_msg += f": {exception}" + messages.error(request, error_msg) + LOG.error(error_msg) + return None + def process_response(self, request: HtmxHttpRequest, response: HttpResponse) -> HttpResponse: if not request.htmx: return response @@ -84,7 +97,13 @@ def process_response(self, request: HtmxHttpRequest, response: HttpResponse) -> has_error_message = any("error" in message.tags for message in storage) storage.used = False if not has_error_message: - messages.error(request, "An error occured while processing your request, please try again") + error_msg = getattr(response, "content", b"") + if isinstance(error_msg, bytes): + error_msg = error_msg.decode("utf-8") + if not error_msg: + error_msg = f"{response.status_code} {response.reason_phrase}" + messages.error(request, f"An unexpected error occured: {error_msg}. Please try again") + LOG.error("Unhandled exception: %s", error_msg) # HTMX doesn't swap content for response codes >=400. However, we do want to show # the new messages, so we need to rewrite the response to 200, and make sure it only # swaps the oob notification content