While trying to raise a rest_framework.serializers.ValidationError, I noticed that the following code does not change the status_code
raise serializers.ValidationError('An error', code=HTTP_404_NOT_FOUND)
After some checks, however, I found that I had to do
api_exception = serializers.ValidationError(err_obj)
api_exception.status_code = HTTP_404_NOT_FOUND
raise api_exception
I just wanted to suggest that we add the status_code property to the ValidationError as this is more intuitive. What do you think
The following ought to change the status code to 404
raise serializers.ValidationError('An error', status_code=HTTP_404_NOT_FOUND)
Why don't you just use NotFound?
I don't think this is behavior we want to support, and I don't think the fix will function like you expect. Serializer errors are collected and re-raised under a new ValidationError instance, so your provided status_code wouldn't be used by the exception handler.
To get custom status codes to work, the exception handler would need to have special handling that walks the validation errors, collecting all status_codes, then determine which one to use. e.g., if you have a combination of 400's and 404's, your handler would need to somehow determine which status code should be raised.
If you do want to proceed with this, I would recommend creating a custom ValidationError subclass that sets its own status code, then write an exception handler that does whatever you'd expect it to do.
class MyValidationError(serializers.ValidationError):
status_code = 404