4👍
✅
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,
👤JPG
Source:stackexchange.com