How to override exception messages in django rest framework

后端 未结 2 668
南旧
南旧 2020-12-30 14:07

I am using django class based view and rest framework

object = self.get_object()

In Detail view if object does not exist and i do get reque

2条回答
  •  别那么骄傲
    2020-12-30 14:28

    We can implement a custom exception handler function that returns the custom response in case the object does not exist.

    In case a object does not exist, Http404 exception is raised. So, we will check if the exception raised is Http404 and if that is the case, we will return our custom exception message in the response.

    from rest_framework.views import exception_handler
    from django.http import Http404
    
    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)
    
        if isinstance(exc, Http404):  
            custom_response_data = { 
                'detail': 'This object does not exist.' # custom exception message
            }
            response.data = custom_response_data # set the custom response data on response object
    
        return response
    

    After defining our custom exception handler, we need to add this custom exception handler to our DRF settings.

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

提交回复
热议问题