|
1 | 1 | from typing import List
|
2 |
| -from rest_framework.exceptions import ValidationError |
| 2 | +from rest_framework.exceptions import ValidationError as DRFValidationError |
3 | 3 | from rest_framework.response import Response
|
4 | 4 | from rest_framework import status
|
5 |
| -from rest_framework.views import exception_handler |
| 5 | +from rest_framework.views import exception_handler as drf_exception_handler |
6 | 6 | from rest_framework.utils.serializer_helpers import ReturnDict
|
| 7 | +from django.conf import settings |
| 8 | +from bson.errors import InvalidId as BsonInvalidId |
7 | 9 |
|
8 | 10 | from todo.dto.responses.error_response import ApiErrorDetail, ApiErrorResponse, ApiErrorSource
|
9 |
| - |
10 |
| - |
11 |
| -def handle_exception(exc, context): |
12 |
| - if isinstance(exc, ValidationError): |
13 |
| - return Response( |
14 |
| - ApiErrorResponse( |
15 |
| - statusCode=status.HTTP_400_BAD_REQUEST, |
16 |
| - message="Invalid request", |
17 |
| - errors=format_validation_errors(exc.detail), |
18 |
| - ).model_dump(mode="json", exclude_none=True), |
19 |
| - status=status.HTTP_400_BAD_REQUEST, |
20 |
| - ) |
21 |
| - return exception_handler(exc, context) |
| 11 | +from todo.constants.messages import ApiErrors, ValidationErrors |
| 12 | +from todo.exceptions.task_exceptions import TaskNotFoundException |
22 | 13 |
|
23 | 14 |
|
24 | 15 | def format_validation_errors(errors) -> List[ApiErrorDetail]:
|
25 | 16 | formatted_errors = []
|
26 | 17 | if isinstance(errors, ReturnDict | dict):
|
27 | 18 | for field, messages in errors.items():
|
28 |
| - if isinstance(messages, list): |
29 |
| - for message in messages: |
30 |
| - formatted_errors.append(ApiErrorDetail(detail=message, source={ApiErrorSource.PARAMETER: field})) |
31 |
| - elif isinstance(messages, dict): |
32 |
| - nested_errors = format_validation_errors(messages) |
33 |
| - formatted_errors.extend(nested_errors) |
34 |
| - else: |
35 |
| - formatted_errors.append(ApiErrorDetail(detail=messages, source={ApiErrorSource.PARAMETER: field})) |
| 19 | + details = messages if isinstance(messages, list) else [messages] |
| 20 | + for message_detail in details: |
| 21 | + if isinstance(message_detail, dict): |
| 22 | + nested_errors = format_validation_errors(message_detail) |
| 23 | + formatted_errors.extend(nested_errors) |
| 24 | + else: |
| 25 | + formatted_errors.append( |
| 26 | + ApiErrorDetail(detail=str(message_detail), source={ApiErrorSource.PARAMETER: field}) |
| 27 | + ) |
| 28 | + elif isinstance(errors, list): |
| 29 | + for message_detail in errors: |
| 30 | + formatted_errors.append(ApiErrorDetail(detail=str(message_detail))) |
36 | 31 | return formatted_errors
|
| 32 | + |
| 33 | + |
| 34 | +def handle_exception(exc, context): |
| 35 | + response = drf_exception_handler(exc, context) |
| 36 | + task_id = context.get("kwargs", {}).get("task_id") |
| 37 | + |
| 38 | + error_list = [] |
| 39 | + status_code = status.HTTP_500_INTERNAL_SERVER_ERROR |
| 40 | + determined_message = ApiErrors.UNEXPECTED_ERROR_OCCURRED |
| 41 | + |
| 42 | + if isinstance(exc, TaskNotFoundException): |
| 43 | + status_code = status.HTTP_404_NOT_FOUND |
| 44 | + detail_message_str = str(exc) |
| 45 | + determined_message = detail_message_str |
| 46 | + error_list.append( |
| 47 | + ApiErrorDetail( |
| 48 | + source={ApiErrorSource.PATH: "task_id"} if task_id else None, |
| 49 | + title=ApiErrors.RESOURCE_NOT_FOUND_TITLE, |
| 50 | + detail=detail_message_str, |
| 51 | + ) |
| 52 | + ) |
| 53 | + elif isinstance(exc, BsonInvalidId): |
| 54 | + status_code = status.HTTP_400_BAD_REQUEST |
| 55 | + determined_message = ValidationErrors.INVALID_TASK_ID_FORMAT |
| 56 | + error_list.append( |
| 57 | + ApiErrorDetail( |
| 58 | + source={ApiErrorSource.PATH: "task_id"} if task_id else None, |
| 59 | + title=ApiErrors.VALIDATION_ERROR, |
| 60 | + detail=ValidationErrors.INVALID_TASK_ID_FORMAT, |
| 61 | + ) |
| 62 | + ) |
| 63 | + elif ( |
| 64 | + isinstance(exc, ValueError) |
| 65 | + and hasattr(exc, "args") |
| 66 | + and exc.args |
| 67 | + and (exc.args[0] == ValidationErrors.INVALID_TASK_ID_FORMAT or exc.args[0] == "Invalid ObjectId format") |
| 68 | + ): |
| 69 | + status_code = status.HTTP_400_BAD_REQUEST |
| 70 | + determined_message = ValidationErrors.INVALID_TASK_ID_FORMAT |
| 71 | + error_list.append( |
| 72 | + ApiErrorDetail( |
| 73 | + source={ApiErrorSource.PATH: "task_id"} if task_id else None, |
| 74 | + title=ApiErrors.VALIDATION_ERROR, |
| 75 | + detail=ValidationErrors.INVALID_TASK_ID_FORMAT, |
| 76 | + ) |
| 77 | + ) |
| 78 | + elif ( |
| 79 | + isinstance(exc, ValueError) and hasattr(exc, "args") and exc.args and isinstance(exc.args[0], ApiErrorResponse) |
| 80 | + ): |
| 81 | + api_error_response = exc.args[0] |
| 82 | + return Response( |
| 83 | + data=api_error_response.model_dump(mode="json", exclude_none=True), status=api_error_response.statusCode |
| 84 | + ) |
| 85 | + elif isinstance(exc, DRFValidationError): |
| 86 | + status_code = status.HTTP_400_BAD_REQUEST |
| 87 | + determined_message = "Invalid request" |
| 88 | + error_list = format_validation_errors(exc.detail) |
| 89 | + if not error_list and exc.detail: |
| 90 | + error_list.append(ApiErrorDetail(detail=str(exc.detail), title=ApiErrors.VALIDATION_ERROR)) |
| 91 | + |
| 92 | + else: |
| 93 | + if response is not None: |
| 94 | + status_code = response.status_code |
| 95 | + if isinstance(response.data, dict) and "detail" in response.data: |
| 96 | + detail_str = str(response.data["detail"]) |
| 97 | + determined_message = detail_str |
| 98 | + error_list.append(ApiErrorDetail(detail=detail_str, title=detail_str)) |
| 99 | + elif isinstance(response.data, list): |
| 100 | + for item_error in response.data: |
| 101 | + error_list.append(ApiErrorDetail(detail=str(item_error), title=determined_message)) |
| 102 | + else: |
| 103 | + error_list.append( |
| 104 | + ApiErrorDetail( |
| 105 | + detail=str(response.data) if settings.DEBUG else ApiErrors.INTERNAL_SERVER_ERROR, |
| 106 | + title=determined_message, |
| 107 | + ) |
| 108 | + ) |
| 109 | + else: |
| 110 | + error_list.append( |
| 111 | + ApiErrorDetail( |
| 112 | + detail=str(exc) if settings.DEBUG else ApiErrors.INTERNAL_SERVER_ERROR, title=determined_message |
| 113 | + ) |
| 114 | + ) |
| 115 | + |
| 116 | + if not error_list and not ( |
| 117 | + isinstance(exc, ValueError) and hasattr(exc, "args") and exc.args and isinstance(exc.args[0], ApiErrorResponse) |
| 118 | + ): |
| 119 | + default_detail_str = str(exc) if settings.DEBUG else ApiErrors.INTERNAL_SERVER_ERROR |
| 120 | + |
| 121 | + error_list.append(ApiErrorDetail(detail=default_detail_str, title=determined_message)) |
| 122 | + |
| 123 | + final_response_data = ApiErrorResponse( |
| 124 | + statusCode=status_code, |
| 125 | + message=determined_message, |
| 126 | + errors=error_list, |
| 127 | + ) |
| 128 | + return Response(data=final_response_data.model_dump(mode="json", exclude_none=True), status=status_code) |
0 commit comments