generated from Real-Dev-Squad/website-template
-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add exception handler for validation errors
- Loading branch information
1 parent
39d1972
commit 4220a2c
Showing
2 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from typing import List | ||
from rest_framework.exceptions import ValidationError | ||
from rest_framework.response import Response | ||
from rest_framework import status | ||
from rest_framework.views import exception_handler | ||
from rest_framework.utils.serializer_helpers import ReturnDict | ||
|
||
from todo.dto.responses.error_response import ApiErrorDetail, ApiErrorResponse, ApiErrorSource | ||
|
||
|
||
def handle_exception(exc, context): | ||
if isinstance(exc, ValidationError): | ||
return Response( | ||
ApiErrorResponse( | ||
statusCode=status.HTTP_400_BAD_REQUEST, | ||
message="Invalid request", | ||
errors=format_validation_errors(exc.detail), | ||
).model_dump(mode="json", exclude_none=True), | ||
status=status.HTTP_400_BAD_REQUEST, | ||
) | ||
return exception_handler(exc, context) | ||
|
||
|
||
def format_validation_errors(errors) -> List[ApiErrorDetail]: | ||
formatted_errors = [] | ||
if isinstance(errors, ReturnDict | dict): | ||
for field, messages in errors.items(): | ||
if isinstance(messages, list): | ||
for message in messages: | ||
formatted_errors.append(ApiErrorDetail(detail=message, source={ApiErrorSource.PARAMETER: field})) | ||
elif isinstance(messages, dict): | ||
nested_errors = format_validation_errors(messages) | ||
formatted_errors.extend(nested_errors) | ||
else: | ||
formatted_errors.append(ApiErrorDetail(detail=messages, source={ApiErrorSource.PARAMETER: field})) | ||
return formatted_errors |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters