Tastypie-django自定义错误处理

mak*_*m-s 8 django error-handling tastypie

我想返回一些JSON响应,而不是只返回带有错误代码的标头.在tastypie中是否有办法处理这样的错误?

mak*_*m-s 5

最终想出来了.如果有其他人需要,这是一个很好的资源.http://gist.github.com/1116962

class YourResource(ModelResource):

    def wrap_view(self, view):
        """
        Wraps views to return custom error codes instead of generic 500's
        """
        @csrf_exempt
        def wrapper(request, *args, **kwargs):
            try:
                callback = getattr(self, view)
                response = callback(request, *args, **kwargs)

                if request.is_ajax():
                    patch_cache_control(response, no_cache=True)

                # response is a HttpResponse object, so follow Django's instructions
                # to change it to your needs before you return it.
                # https://docs.djangoproject.com/en/dev/ref/request-response/
                return response
            except (BadRequest, ApiFieldError), e:
                return HttpBadRequest({'code': 666, 'message':e.args[0]})
            except ValidationError, e:
                # Or do some JSON wrapping around the standard 500
                return HttpBadRequest({'code': 777, 'message':', '.join(e.messages)})
            except Exception, e:
                # Rather than re-raising, we're going to things similar to
                # what Django does. The difference is returning a serialized
                # error message.
                return self._handle_500(request, e)

        return wrapper
Run Code Online (Sandbox Code Playgroud)