You can overwrite the tastypie Resource _handle_500() method. The fact that it starts with an underscore does indicate that it is a "private" method and should not be overwritten, but I find it cleaner than overwriting wrap_view() and replicating a lot of logic.
Here is how I use it:
from tastypie import http from tastypie.resources import ModelResource from tastypie.exceptions import TastypieError class MyResource(ModelResource): class Meta: queryset = MyModel.objects.all() fields = ('my', 'fields') def _handle_500(self, request, exception): if isinstance(exception, TastypieError): data = { 'error_message': getattr( settings, 'TASTYPIE_CANNED_ERROR', 'Sorry, this request could not be processed.' ), } return self.error_response( request, data, response_class=http.HttpApplicationError ) else: return super(MyResource, self)._handle_500(request, exception)
In this case, I catch all Tastypie errors by checking if the exception instance of TastypieError and returns a JSON response with the message "Sorry, this request could not be processed." If this is another exception, I call the parent _handle_500 with super() , which will create a django error page in development mode or send_admins() in send_admins() mode.
If you want to have a specific JSON response for a specific exception, just do an isinstance() check for the specific exception. Here are all the Tastypie exceptions:
https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py
Actually, I think there should be a better / cleaner way to do this in Tastypie, so I opened a ticket on my github.
rednaw
source share