Prevent Unhandled jQuery AJAX Error

2019-02-11 10:28发布

I know how to receive server data or error. There are many ways. For example:

$.ajax({
    type: "get",
    url: "/widgets/",
    success: function (data, text) {
        console.log('this is a data');
    },
    error: function (request, status, error) {
        console.log('this is an error');
    }
});

Please see this image:

result in chrome developer console

I have my error function and I do what I need there. How can I prevent error in the first line. I have tested 4xx and 5xx errors but no difference. I know that end user does not see this error when developer console is hidden.

I need this to design an API. I know that I can send 200 responses from server with an additional argument that show that this is an error or a success result.

But if I can send 4xx or 5xx responses then there is no need to extra argument. This way has some additional gains for me. For example I can apply success result to my client side models without worry about additional args.

Thank you

1条回答
该账号已被封号
2楼-- · 2019-02-11 10:58

AFAIK you cannot make the red thingies go away, when returning error status-codes (4xx, 5xx). They are used by the browser to indicate that something might have not gone as expected. Still these are mere decorations, since 4xx and 5xx status codes are perfectly valid, so I don't see a reason for you wanting to eliminate them.

As you said yourself, your other alternative would be sending "200 responses from server with an additional argument that show that this is an error or a success result".

I certainly recommend using the 4xx and 5xx codes though (that's what they are designed for) and stop worrying about browser's heads-up warnings in developer console (aka red thingies).

See also this and this questions that refer to similar errors when fetching other kinds of resources (images, files etc). The errors you see are actually of the same nature.

查看更多
登录 后发表回答