Tôi muốn trả lại một số phản hồi JSON thay vì chỉ trả về tiêu đề có mã lỗi. Có cách nào trong ngon để xử lý các lỗi như vậy không?Xử lý lỗi tùy chỉnh Tastypie-django
Trả lời
Tìm ra nó cuối cùng. Đây là một tài nguyên tốt để xem xét, nếu có ai khác cần nó. 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
Bạn có thể ghi đè lên Resource
phương pháp tastypie của _handle_500()
. Thực tế là nó bắt đầu với một gạch dưới thực sự chỉ ra rằng đây là một phương pháp "tư nhân" và không nên được ghi đè, nhưng tôi tìm thấy nó một cách sạch hơn so với việc phải ghi đè lên wrap_view()
và sao chép rất nhiều logic.
Đây là cách tôi sử dụng nó:
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)
Trong trường hợp này tôi bắt tất cả các lỗi Tastypie bằng cách kiểm tra nếu exception
là một thể hiện của TastypieError
và trả về một phản ứng JSON với thông điệp "Xin lỗi, yêu cầu này có thể không được xử lý. " Nếu đó là một ngoại lệ khác, tôi gọi phụ huynh _handle_500
bằng cách sử dụng super()
, điều này sẽ tạo trang lỗi django ở chế độ phát triển hoặc send_admins()
ở chế độ sản xuất.
Nếu bạn muốn có phản hồi JSON cụ thể cho một ngoại lệ cụ thể, chỉ cần thực hiện kiểm tra isinstance()
về một ngoại lệ cụ thể. Dưới đây là tất cả các trường hợp ngoại lệ Tastypie:
https://github.com/toastdriven/django-tastypie/blob/master/tastypie/exceptions.py
Thật sự tôi nghĩ rằng cần có một/cách tốt hơn sạch hơn để làm điều này trong Tastypie, vì vậy tôi opened a ticket trên github của họ.
cũng đã tìm ra. Đây là một tài nguyên tốt để xem xét, nếu có ai khác cần nó. https://gist.github.com/1116962 –
Nếu có thể, hãy dọn dẹp và làm cho nó trở thành Câu trả lời để giúp cộng đồng – Dave