I have a custom middleware where I check whether incoming requests have a cookie present or not. If the cookie is not present, then it shows KeyError:
.
[15/May/2021 18:00:05] "GET /api/auth/profile/ HTTP/1.1" 500 62653
Internal Server Error: /
Traceback (most recent call last):
File "F:\<dir>\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "F:\<dirs\to\middleware>\middleware.py", line 49, in __call__
myCookie = request.COOKIES['my_cookie']
KeyError: 'my_cookie'
I want it to return only a 500 Internal Server Error
if the cookie is not present. How do I do this?
This is my middleware:
class AuthMiddleware:
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
if request.path == '/api/auth/profile/':
try:
myCookie = request.COOKIES['my_cookie']
// do something with the cookie
return self.get_response(request)
except jwt.ExpiredSignatureError:
// do something
return self.get_response(request)
Here, I only check whether the token has expired but I couldn't add mechanism to handle a KeyError
. How do I do this?