ghazi-git / drf-standardized-errors

Standardize your DRF API error responses
https://drf-standardized-errors.readthedocs.io/en/latest/
MIT License
257 stars 15 forks source link

Can't include custom errors! #88

Closed omargawdat closed 1 month ago

omargawdat commented 1 month ago

` drf-spectacular==0.27.2

drf-standardized-errors[openapi]==0.14.1 `

Hello, I am following the documentation but still can't add a custom error to the validations errors !!

image

My code:

` class CustomEmailField(serializers.EmailField): default_error_messages = { 'unknown_email_domain': 'Email addresses ending with @example.com are not allowed.' }

def __init__(self, **kwargs):
    super().__init__(**kwargs)
    self.validators.append(self.validate_email_domain)

def validate_email_domain(self, value):
    if value.lower().endswith('@example.com'):
        self.fail('unknown_email_domain')
    return value

class EventSerializer(serializers.ModelSerializer): email = CustomEmailField()

class Meta:
    model = Event
    fields = ['id', 'name', 'email', 'start_date', 'end_date']

class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = CustomSerializer

`

Swagger 400 errors:

{ "errors": [ { "attr": "non_field_errors", "code": "invalid", "detail": "string" }, { "attr": "name", "code": "blank", "detail": "string" }, { "attr": "email", "code": "blank", "detail": "string" }, { "attr": "start_date", "code": "datetime", "detail": "string" }, { "attr": "end_date", "code": "datetime", "detail": "string" } ] }

config

` REST_FRAMEWORK = { "EXCEPTION_HANDLER": "drf_standardized_errors.handler.exception_handler", "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_SCHEMA_CLASS": "drf_standardized_errors.openapi.AutoSchema", "DEFAULT_THROTTLE_CLASSES": [ "rest_framework.throttling.AnonRateThrottle", "rest_framework.throttling.UserRateThrottle", ], "DEFAULT_THROTTLE_RATES": {"anon": "600/day", "user": "2000/day"}, } DRF_STANDARDIZED_ERRORS = { "ENABLE_IN_DEBUG_FOR_UNHANDLED_EXCEPTIONS": True, "EXCEPTION_HANDLER_CLASS": "config.custom_exception_handler.CustomExceptionHandler", } CORS_URLS_REGEX = r"^/api/.*$"

SPECTACULAR_SETTINGS = { "TITLE": "projectname API", "DESCRIPTION": "Documentation of API endpoints of projectname App", "VERSION": "1.0.0", "SCHEMA_PATH_PREFIX": "/api/", "ENUM_NAME_OVERRIDES": { "ValidationErrorEnum": "drf_standardized_errors.openapi_serializers.ValidationErrorEnum.choices", "ClientErrorEnum": "drf_standardized_errors.openapi_serializers.ClientErrorEnum.choices", "ServerErrorEnum": "drf_standardized_errors.openapi_serializers.ServerErrorEnum.choices", "ErrorCode401Enum": "drf_standardized_errors.openapi_serializers.ErrorCode401Enum.choices", "ErrorCode403Enum": "drf_standardized_errors.openapi_serializers.ErrorCode403Enum.choices", "ErrorCode404Enum": "drf_standardized_errors.openapi_serializers.ErrorCode404Enum.choices", "ErrorCode405Enum": "drf_standardized_errors.openapi_serializers.ErrorCode405Enum.choices", "ErrorCode406Enum": "drf_standardized_errors.openapi_serializers.ErrorCode406Enum.choices", "ErrorCode415Enum": "drf_standardized_errors.openapi_serializers.ErrorCode415Enum.choices", "ErrorCode429Enum": "drf_standardized_errors.openapi_serializers.ErrorCode429Enum.choices", "ErrorCode500Enum": "drf_standardized_errors.openapi_serializers.ErrorCode500Enum.choices", }, "POSTPROCESSING_HOOKS": ["drf_standardized_errors.openapi_hooks.postprocess_schema_enums"], }

class CustomExceptionHandler(ExceptionHandler): def convert_known_exceptions(self, exc: Exception) -> Exception: if isinstance(exc, (SimpleAuthenticationFailed, InvalidToken)): detail = exc.detail["detail"] if isinstance(exc.detail, dict) else exc.detail code = exc.detail.get("code") if isinstance(exc.detail, dict) else exc.default_code return DRFAuthenticationFailed(detail, code=code) else: return super().convert_known_exceptions(exc)

`

ghazi-git commented 1 month ago

can you make sure to check the API schema to see all possible errors? what you added under "Swagger 400 errors" seems to be from the example generated by swagger ui, rather than the API schema generated by drf-spectacular (you can check the API schema as shown in the screenshot). Otherwise, can you provide the json/yaml of the API schema generated for the code you provided? image

omargawdat commented 1 month ago

aha, I thought it could be displayed in examples thanks for your help !!