Django REST Exceptions

后端 未结 2 886
谎友^
谎友^ 2021-01-30 13:58

I currently have some code for a view based on the Django REST Framework. Ive been using a customer exception class, but ideally I want to use the inbuilt Django REST exceptions

相关标签:
2条回答
  • 2021-01-30 14:48

    The Django REST framework provides several built in exceptions, which are mostly subclasses of DRF's APIException.

    You can raise exceptions in your view like you normally would in Python:

    from rest_framework.exceptions import APIException
    
    def my_view(request):
        raise APIException("There was a problem!")
    

    You could also create your own custom exception by inheriting from APIException and setting status_code and default_detail. Some of the built in ones are: ParseError, AuthenticationFailed, NotAuthenticated, PermissionDenied, NotFound, NotAcceptable, ValidationError, etc.

    These will then get converted to a Response by the REST Framework's exception handler. Each exception is associated with a status code that is added to the Response. By default the exception handler is set to the built in handler:

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
    }
    

    But you can set it to your own custom exception handler if you want to convert the exceptions yourself by changing this in your settings.py file:

    REST_FRAMEWORK = {
        'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
    }
    

    And then create the custom handler in that location:

    from rest_framework.views import exception_handler
    
    def custom_exception_handler(exc, context):
        # Call REST framework's default exception handler first,
        # to get the standard error response.
        response = exception_handler(exc, context)
    
        # Now add the HTTP status code to the response.
        if response is not None:
            response.data['status_code'] = response.status_code
    
        return response
    
    0 讨论(0)
  • 2021-01-30 14:48

    You can use the build in DRF exception, just import and raise

    from rest_framework.exceptions import
    ...
    raise ParseError('I already have a status code!')
    
    0 讨论(0)
提交回复
热议问题