celiao / django-rest-authemail

A RESTful API for user signup and authentication using email addresses.
GNU General Public License v3.0
314 stars 91 forks source link

Views should raise Exceptions instead of returning Response with 'HTTP_400_BAD_REQUEST' #56

Open pjrobertson opened 2 years ago

pjrobertson commented 2 years ago

Right now, if views encounter an error (invalid fields etc.) they return a Response object with the status code set.

However, instead the view should raise an Exception (e.g. ValidationError). This means that Django rest can handle the exception appropriately, and then set the status code itself. This is useful, for example, if you have a custom exception_handler set.

In all views, code like this:


    def get(self, request, format=None):
        code = request.GET.get('code', '')
        verified = SignupCode.objects.set_user_is_verified(code)

        if verified:
            try:
                signup_code = SignupCode.objects.get(code=code)
                signup_code.delete()
            except SignupCode.DoesNotExist:
                pass
            content = {'success': _('Email address verified.')}
            return Response(content, status=status.HTTP_200_OK)
        else:
            content = {'detail': _('Unable to verify user.')}
            return Response(content, status=status.HTTP_400_BAD_REQUEST)

Should be changed to:


    def get(self, request, format=None):
        code = request.GET.get('code', '')
        verified = SignupCode.objects.set_user_is_verified(code)

        if verified:
            try:
                signup_code = SignupCode.objects.get(code=code)
                signup_code.delete()
            except SignupCode.DoesNotExist:
                pass
            content = {'success': _('Email address verified.')}
            return Response(content, status=status.HTTP_200_OK)
        else:
            raise ValidationError( _('Unable to verify user.'))