def exception_handler(exc, context): # Import this here to avoid potential edge-case circular imports, which # crashes with: # "ImportError: Could not import 'rest_framework_json_api.parsers.JSONParser' for API setting # 'DEFAULT_PARSER_CLASSES'. ImportError: cannot import name 'exceptions'.'" # # Also see: https://github.com/django-json-api/django-rest-framework-json-api/issues/158 from rest_framework.views import exception_handler as drf_exception_handler # Render exception with DRF response = drf_exception_handler(exc, context) if not response: return response # Use regular DRF format if not rendered by DRF JSON API and not uniform is_json_api_view = rendered_with_json_api(context['view']) is_uniform = json_api_settings.UNIFORM_EXCEPTIONS if not is_json_api_view and not is_uniform: return response # Convert to DRF JSON API error format response = utils.format_drf_errors(response, context, exc) # Add top-level 'errors' object when not rendered by DRF JSON API if not is_json_api_view: response.data = utils.format_errors(response.data) return response
def handle_exception(self, exc): if isinstance(exc, exceptions.ValidationError): # some require that validation errors return 422 status # for example ember-data (isInvalid method on adapter) exc.status_code = HTTP_422_UNPROCESSABLE_ENTITY # exception handler can't be set on class so you have to # override the error response in this method response = super(JsonApiViewSet, self).handle_exception(exc) context = self.get_exception_handler_context() return format_drf_errors(response, context, exc)
def exception_handler(exc, context): # Import this here to avoid potential edge-case circular imports, which # crashes with: # "ImportError: Could not import 'rest_framework_json_api.parsers.JSONParser' for API setting # 'DEFAULT_PARSER_CLASSES'. ImportError: cannot import name 'exceptions'.'" # # Also see: https://github.com/django-json-api/django-rest-framework-json-api/issues/158 from rest_framework.views import exception_handler as drf_exception_handler # Render exception with DRF response = drf_exception_handler(exc, context) if not response: return unhandled_drf_exception_handler(exc, context) if response.status_code == status.HTTP_400_BAD_REQUEST: if isinstance(exc.detail, dict): for field, detail in list(exc.detail.items()): if isinstance(detail, dict): for key in detail.keys(): exc.detail[f'{field}.{key}'] = detail[key] exc.detail.pop(field) # Use regular DRF format if not rendered by DRF JSON API and not uniform is_json_api_view = rendered_with_json_api(context['view']) is_uniform = getattr(settings, 'JSON_API_UNIFORM_EXCEPTIONS', False) if not is_json_api_view and not is_uniform: return response # Convert to DRF JSON API error format response = utils.format_drf_errors(response, context, exc) # Add top-level 'errors' object when not rendered by DRF JSON API if not is_json_api_view: response.data = utils.format_errors(response.data) return response