Просмотр исходного кода

Implement a custom 404 handler to enable Sentry reporting

jeremystretch 3 лет назад
Родитель
Сommit
c146596564
3 измененных файлов с 14 добавлено и 3 удалено
  1. 2 0
      docs/administration/error-reporting.md
  2. 1 0
      netbox/netbox/urls.py
  3. 11 3
      netbox/netbox/views/__init__.py

+ 2 - 0
docs/administration/error-reporting.md

@@ -25,3 +25,5 @@ SENTRY_TAGS = {
 ```
 
 Once the configuration has been saved, restart the NetBox service.
+
+To test Sentry operation, try generating a 404 (page not found) error by navigating to an invalid URL, such as `https://netbox/404-error-testing`. After receiving a 404 response from the NetBox server, you should see the issue appear shortly in Sentry.

+ 1 - 0
netbox/netbox/urls.py

@@ -100,4 +100,5 @@ urlpatterns = [
     path('{}'.format(settings.BASE_PATH), include(_patterns))
 ]
 
+handler404 = 'netbox.views.handler_404'
 handler500 = 'netbox.views.server_error'

+ 11 - 3
netbox/netbox/views/__init__.py

@@ -2,7 +2,6 @@ import platform
 import sys
 
 from django.conf import settings
-from django.contrib.contenttypes.models import ContentType
 from django.core.cache import cache
 from django.db.models import F
 from django.http import HttpResponseServerError
@@ -11,9 +10,10 @@ from django.template import loader
 from django.template.exceptions import TemplateDoesNotExist
 from django.urls import reverse
 from django.views.decorators.csrf import requires_csrf_token
-from django.views.defaults import ERROR_500_TEMPLATE_NAME
+from django.views.defaults import ERROR_500_TEMPLATE_NAME, page_not_found
 from django.views.generic import View
 from packaging import version
+from sentry_sdk import capture_message
 
 from circuits.models import Circuit, Provider
 from dcim.models import (
@@ -190,13 +190,21 @@ class StaticMediaFailureView(View):
     """
     Display a user-friendly error message with troubleshooting tips when a static media file fails to load.
     """
-
     def get(self, request):
         return render(request, 'media_failure.html', {
             'filename': request.GET.get('filename')
         })
 
 
+def handler_404(request, exception):
+    """
+    Wrap Django's default 404 handler to enable Sentry reporting.
+    """
+    capture_message("Page not found", level="error")
+
+    return page_not_found(request, exception)
+
+
 @requires_csrf_token
 def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
     """