如何将错误响应从django发送到ajax

时间:2022-10-09 11:42:43

I have this Ajax request:

我有这个Ajax请求:

    $.ajax({
            url: "my_url",
            headers: {'X-CSRFToken': '{{ csrf_token }}'},
            type: "post",
            data:{x:1
                 },
            success: function(response, textStatus, xhr) {
                alert(response + textStatus + xhr);

            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(xhr.status + ' Error: ' + thrownError);
            }
          });

}

on the Django side, I sometimes want to propagate errors. If I raise an exception, it will propagate as a 500 response INTERNAL ERORR. But I want to display an error message. so I tried

在Django方面,我有时希望传播错误。如果我提出一个异常,它将作为500响应内部ERORR传播。但是我想显示一个错误消息。所以我试着

return HttpResponse("Bad permissions", status=500)

but I'm not able to capture the custom error message. Any ideas?

但是我不能捕获自定义错误消息。什么好主意吗?


For those of you how want to know what worked:

对于那些想知道什么起作用的人:

// javascript in the template
function send(){
    $.ajax({
            url: "/get_pens/",
            headers: {'X-CSRFToken': '{{ csrf_token }}'},
            type: "post",
            data:{x:1
                 },
            dataType: "json",
            success: function(response, textStatus, xhr) {
                alert('Success: ' + response + textStatus + xhr);

            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(xhr.status + ' Error: ' + xhr.responseJSON['err']);
            }
          });
}
// views.py
def get_pens(request):
    pens = []
    response = HttpResponse(json.dumps({'pens': pens, 'err': 'some custom error message'}), 
        content_type='application/json')
    response.status_code = 400
    return response

1 个解决方案

#1


3  

One way you can approach this is as following,

一种方法是,

You have proper try exception blocks around the code around the block which are prone to raise exceptions. There are lot many Exception subclasses which can cover the type of the exception being raised for eg. Model.DoesNotExist. In those exception blocks, you simply create appropriate HttpResponse and send it back. Lets take an example here.

您在块周围的代码周围有合适的try exception块,这很容易引发异常。有许多异常子类可以覆盖为eg引发的异常的类型。Model.DoesNotExist。在这些异常块中,您只需创建适当的HttpResponse并将其发送回来。举个例子。

class DemoView(View):
    def post(self, request, oid, *args, **kwargs):
    try:
        object = Model.objects.get(id=oid)
    except Model.DoesNotExist:
        return HttpResponseNotFound('error message')

This way your error block is executed in your ajax function. You might consider it as a way to go and seems a right approach to me.

这样,错误块在ajax函数中执行。你可能会认为这是一条路,对我来说似乎是一条正确的路。

Update: Based on the comment you(OP) made below, you can have a response created in following fashion

更新:根据下面的评论,您可以按照以下方式创建响应

def bad_request(message):
    response = HttpResponse(json.dumps({'message': message}), 
        content_type='application/json')
    response.status_code = 400
    return response

When you want to return status 400, you simply do,

当你想要返回400状态时,你只要做,

return bad_request(message='This is a bad request')

So following this, in your ajax error function, you can use following to get that message,

接下来,在ajax error函数中,你可以使用following来获取消息,

xhr.responseJSON.message

#1


3  

One way you can approach this is as following,

一种方法是,

You have proper try exception blocks around the code around the block which are prone to raise exceptions. There are lot many Exception subclasses which can cover the type of the exception being raised for eg. Model.DoesNotExist. In those exception blocks, you simply create appropriate HttpResponse and send it back. Lets take an example here.

您在块周围的代码周围有合适的try exception块,这很容易引发异常。有许多异常子类可以覆盖为eg引发的异常的类型。Model.DoesNotExist。在这些异常块中,您只需创建适当的HttpResponse并将其发送回来。举个例子。

class DemoView(View):
    def post(self, request, oid, *args, **kwargs):
    try:
        object = Model.objects.get(id=oid)
    except Model.DoesNotExist:
        return HttpResponseNotFound('error message')

This way your error block is executed in your ajax function. You might consider it as a way to go and seems a right approach to me.

这样,错误块在ajax函数中执行。你可能会认为这是一条路,对我来说似乎是一条正确的路。

Update: Based on the comment you(OP) made below, you can have a response created in following fashion

更新:根据下面的评论,您可以按照以下方式创建响应

def bad_request(message):
    response = HttpResponse(json.dumps({'message': message}), 
        content_type='application/json')
    response.status_code = 400
    return response

When you want to return status 400, you simply do,

当你想要返回400状态时,你只要做,

return bad_request(message='This is a bad request')

So following this, in your ajax error function, you can use following to get that message,

接下来,在ajax error函数中,你可以使用following来获取消息,

xhr.responseJSON.message