Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: better exception handling in django #78

Closed
wants to merge 5 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 30 additions & 6 deletions backend/backend/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,42 @@
from rest_framework.views import exception_handler
from django.http import HttpResponse
from rest_framework import status


def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
print("EXCEPTION", exc)

# set 404 as default response code
status_code = 404

# Now add the HTTP status code to the response.
if response is not None:
status_code = response.status_code
return response # Return the default response if it's available

# Define custom mappings of exception classes to HTTP status codes
exception_mappings = {
# Authentication exceptions
'AuthenticationFailed': status.HTTP_401_UNAUTHORIZED,

# Permission exceptions
'PermissionDenied': status.HTTP_403_FORBIDDEN,

# Validation exceptions
'ValidationError': status.HTTP_400_BAD_REQUEST,

# Not Found exception
'ObjectDoesNotExist': status.HTTP_404_NOT_FOUND,

# Any other unhandled exceptions
Exception: status.HTTP_500_INTERNAL_SERVER_ERROR,
}

# Get the exception class of the raised exception
exception_class = exc.__class__

# Check if the exception class is in the mappings
if exception_class in exception_mappings:
status_code = exception_mappings[exception_class]
else:
# Default to 500 for unhandled exceptions
status_code = exception_mappings[Exception]

return HttpResponse(status=status_code)
Loading