Django rest frameworkで認証エラー時のレスポンスをカスタマイズ

認証モデルのカスタマイズ方法はこちらを参考にさせて頂きました。
django-rest-framework-jwtの認証をカスタマイズする方法 - らっちゃいブログ

sampleView.py

class SampleView(APIView):
    
  permission_classes = (permissions.IsAuthenticated,) # 認証チェック
    
  def post(self, request, format=None):
   ~~

こんな感じでViewを定義するだけで

{"detail":"Incorrect authentication credentials."}

こういうレスポンスを返してくれる。優しい

でもこのレスポンスをこちらの仕様に合わせてカスタマイズしたい。
→ 認証エラー時のハンドルはAPIViewで行なっていたので、該当箇所をオーバーライドしてみた。

sampleAuth.py

from rest_framework_jwt.settings import api_settings
from rest_framework.views import APIView
from rest_framework.response import Response


class APIViewWithTokenCheck(APIView):
    ''' APIViewに対してエラーレスポンス返却処理をオーバーライド '''
    def handle_exception(self, exc):
        """
        Handle any exception that occurs, by returning an appropriate response,
        or re-raising the error.
        """
        if isinstance(exc, (exceptions.NotAuthenticated,
                            exceptions.AuthenticationFailed)):
            return Response(  #返却値をカスタマイズ
                data={
                'status': False,
                'error_code':'999_auth_error',
                },
                status=status.HTTP_401_UNAUTHORIZED)

        exception_handler = self.get_exception_handler()

        context = self.get_exception_handler_context()
        response = exception_handler(exc, context)

        if response is None:
            self.raise_uncaught_exception(exc)

        response.exception = True
        return response

これでレスポンスがカスタマイズされる。 {"status":false,"error_code":"999_auth_error"}

ベストなやり方かは不明…