Prometheus
Prometheus

Reputation: 33625

Twitter style errors for Django TastyPie

I need to find a common way to report errors back to my users with TastyPie for example looking at twitter this is how they always show errors:

{"errors":[{"message":"Sorry, that page does not exist","code":34}]}

So errors are an array of errors.

I tried to do something along the same lines in TastyPie like this:

def is_valid(self, bundle, request=None):
        errors = {}
        # Check if user already exists before allowing API to create a new one.
        this_email = bundle.data.get('email', None)
        object_count = Member.objects.filter(email=this_email).count()
        if object_count != 0:
            errors['ERRORS'] = 'Duplicate email address'
        return errors

But as you can see its not very DRY and the output is not right:

{"object_register":{"ERRORS":"Sorry, that page does not exist"}}

I have also tried:

reply = {}
reply['errors'] = [{'message': 'Sorry we could not log you in.'}]
return self.create_response(request, reply, HttpUnauthorized)

So my question is, it is possible to achieve a 'Twitter' style output for errors using Tatypie in a DRY way? If so any examples?

Upvotes: 0

Views: 41

Answers (1)

mariodev
mariodev

Reputation: 15509

To customize your error output, you can override is_valid method of the resource itself.

MyResource(ModelRecource):
    def is_valid(self, bundle):
        errors = self._meta.validation.is_valid(bundle, bundle.request)

        if errors:
            bundle.errors['errors'] = [errors]
            return False

        return True

Upvotes: 1

Related Questions