Date Modified Tags django / python

Django REST framework by default does not give you errors from a custom validate() method if there are also errors from individual serializer fields.

Should you ever need this, you may find the following code helpful:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class AllErrorsSerializer(serializers.Serializer):
    # Combine field errors and errors from validate()
    # so we can display them all at once.

    def is_valid(self, raise_exception=False):
        super().is_valid(raise_exception=False)

        try:
            self.validate(self.data)
        except serializers.ValidationError as e:
            self._errors['non_field_errors'] = e.detail

        if self._errors and raise_exception:
            raise serializers.ValidationError(self._errors)

        return not bool(self._errors)

We should all write more, and doismellburning convinced me to make this post ;)

P.S.: I also use this custom exception handler:

1
2
3
4
5
6
7
8
def my_exception_handler(exc, context):
    response = exception_handler(exc, context)
    try:
        error_data = exc.get_full_details()
    except Exception:
        return response
    response.data = error_data
    return response

In my experience, implementing client-friendly error handling in my API is surprisingly difficult. I might eventually write more about this.