Search code examples
djangodjango-rest-frameworkdjango-viewsjwtdjango-rest-framework-simplejwt

Custom unauthorized error response in DRF


error page

If any request failed to authenticate this view, the user is getting the default Django-Rest page. How I can customize this response in case of an unauthorized request.

@api_view(['GET'])
@authentication_classes([JWTTokenUserAuthentication])
@permission_classes([IsAuthenticated])
def home_view(request):
-----

Solution

  • You can create a custom EXCEPTION_HANDLER function as,

    from rest_framework.views import exception_handler
    from rest_framework.exceptions import NotAuthenticated
    from rest_framework.response import Response
    
    
    def custom_exception_handler(exc, context):
        if isinstance(exc, NotAuthenticated):
            return Response({"custom_key": "custom message"}, status=401)
    
        # else
        # default case
        return exception_handler(exc, context)

    and then, wire-up this new custom function in your settings as,

    REST_FRAMEWORK = {
        # other settings
        "EXCEPTION_HANDLER": "dotted.path.to.the.custom.function"
    
    }

    and thus, you'll get a result as below,

    enter image description here