How to handle python django rest-framework-api malformed UUID instead of 500?

Viewed 971

When using a malformed UUID in django-rest-framework the server throws an exception and returns status-code 500. The exception ValueError 'badly formed hexadecimal UUID string' isn't handled.

It makes more sense to handle it properly and return a status code 400.

I managed to do that with a custom exception handler but it's a really messy and ugly solution.

I thought about doing it with a custom serializer, but I wasn't sure how to handle this properly and if this is the right django approach.

What do you think?

Cheers.

2 Answers

Adding

lookup_value_regex = '[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}' 

to a view uses django validation to only allow UUIDs to get processed and otherwise it just automatically gets a 404.

https://www.django-rest-framework.org/api-guide/routers/

Example in docs:

class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    lookup_field = 'my_model_id'
    lookup_value_regex = '[0-9a-f]{32}'
Related