Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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):
-----
like image 903
vivek kumar choubey Avatar asked Oct 21 '25 03:10

vivek kumar choubey


1 Answers

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

like image 155
JPG Avatar answered Oct 23 '25 16:10

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!