Explorar o código

Move utilities.api.rest_api_server_error() to utilities.error_handlers.handle_rest_api_exception()

Jeremy Stretch hai 1 ano
pai
achega
19bb808936
Modificáronse 3 ficheiros con 30 adicións e 25 borrados
  1. 4 3
      netbox/netbox/middleware.py
  2. 1 22
      netbox/utilities/api.py
  3. 25 0
      netbox/utilities/error_handlers.py

+ 4 - 3
netbox/netbox/middleware.py

@@ -13,7 +13,8 @@ from django.http import Http404, HttpResponseRedirect
 from extras.context_managers import event_tracking
 from netbox.config import clear_config, get_config
 from netbox.views import handler_500
-from utilities.api import is_api_request, rest_api_server_error
+from utilities.api import is_api_request
+from utilities.error_handlers import handle_rest_api_exception
 
 __all__ = (
     'CoreMiddleware',
@@ -71,7 +72,7 @@ class CoreMiddleware:
 
         # Cleanly handle exceptions that occur from REST API requests
         if is_api_request(request):
-            return rest_api_server_error(request)
+            return handle_rest_api_exception(request)
 
         # Ignore Http404s (defer to Django's built-in 404 handling)
         if isinstance(exception, Http404):
@@ -211,7 +212,7 @@ class MaintenanceModeMiddleware:
                             'operations. Please try again later.'
 
             if is_api_request(request):
-                return rest_api_server_error(request, error=error_message)
+                return handle_rest_api_exception(request, error=error_message)
 
             messages.error(request, error_message)
             return HttpResponseRedirect(request.path_info)

+ 1 - 22
netbox/utilities/api.py

@@ -1,22 +1,16 @@
-import platform
-import sys
-
-from django.conf import settings
 from django.contrib.contenttypes.fields import GenericForeignKey
 from django.core.exceptions import (
     FieldDoesNotExist, FieldError, MultipleObjectsReturned, ObjectDoesNotExist, ValidationError,
 )
 from django.db.models.fields.related import ManyToOneRel, RelatedField
-from django.http import JsonResponse
 from django.urls import reverse
 from django.utils.translation import gettext_lazy as _
-from rest_framework import status
 from rest_framework.serializers import Serializer
 from rest_framework.views import get_view_name as drf_get_view_name
 
 from extras.constants import HTTP_CONTENT_TYPE_JSON
-from netbox.api.fields import RelatedObjectCountField
 from netbox.api.exceptions import GraphQLTypeNotFound, SerializerNotFound
+from netbox.api.fields import RelatedObjectCountField
 from .utils import count_related, dict_to_filter_params, dynamic_import, title
 
 __all__ = (
@@ -27,7 +21,6 @@ __all__ = (
     'get_serializer_for_model',
     'get_view_name',
     'is_api_request',
-    'rest_api_server_error',
 )
 
 
@@ -180,17 +173,3 @@ def get_related_object_by_attrs(queryset, attrs):
         return queryset.get(pk=pk)
     except ObjectDoesNotExist:
         raise ValidationError(_("Related object not found using the provided numeric ID: {id}").format(id=pk))
-
-
-def rest_api_server_error(request, *args, **kwargs):
-    """
-    Handle exceptions and return a useful error message for REST API requests.
-    """
-    type_, error, traceback = sys.exc_info()
-    data = {
-        'error': str(error),
-        'exception': type_.__name__,
-        'netbox_version': settings.VERSION,
-        'python_version': platform.python_version(),
-    }
-    return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

+ 25 - 0
netbox/utilities/error_handlers.py

@@ -1,8 +1,19 @@
+import platform
+import sys
+
+from django.conf import settings
 from django.contrib import messages
 from django.db.models import ProtectedError, RestrictedError
+from django.http import JsonResponse
 from django.utils.html import escape
 from django.utils.safestring import mark_safe
 from django.utils.translation import gettext_lazy as _
+from rest_framework import status
+
+__all__ = (
+    'handle_protectederror',
+    'handle_rest_api_exception',
+)
 
 
 def handle_protectederror(obj_list, request, e):
@@ -32,3 +43,17 @@ def handle_protectederror(obj_list, request, e):
     err_message += ', '.join(dependent_objects)
 
     messages.error(request, mark_safe(err_message))
+
+
+def handle_rest_api_exception(request, *args, **kwargs):
+    """
+    Handle exceptions and return a useful error message for REST API requests.
+    """
+    type_, error, traceback = sys.exc_info()
+    data = {
+        'error': str(error),
+        'exception': type_.__name__,
+        'netbox_version': settings.VERSION,
+        'python_version': platform.python_version(),
+    }
+    return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR)