How to mock a 501 error from ajax call

2019-08-01 13:24发布

问题:

I've got an http 501 error bubbling up in prod from this call:

return $.ajax({
    url: finalUrl,
    success: function (result) {
        console.log('success call result');
        console.log(result);
        finalResult = result;
    },
    data: JSON.stringify(data),
    type: 'PATCH',
    contentType: 'application/json'
});

How can I return a mock simulating the error so I can test a fix outside of production? I looked at the response tab in chrome and I see an HTML message:

<HTML><HEAD>
<TITLE>Unsupported Request</TITLE>
</HEAD><BODY>
<H1>Unsupported Request</H1>
PATCH to http&#58;&#47;&#47;demo&#46;site&#46;com&#47;serviceName&#47;v1&#47;requests&#47;9305e338&#45;666a&#45;e611&#45;8516&#45;000c291891bb not supported.<P>
Reference&#32;&#35;8&#46;f0fd717&#46;1472154919&#46;9959c96
</BODY></HTML>

We suspect that the API is not being hit at all, blocked by a firewall. I don't know if I should expect a string or object in this case? If object, then what are the members of that object?

Fiddler says:

Server: AkamaiGHost
Mime-Version: 1.0
Content-Type: text/html
Content-Length: 350
Expires: Thu, 25 Aug 2016 20:21:49 GMT
Date: Thu, 25 Aug 2016 20:21:49 GMT
Connection: close

回答1:

We suspect that the API is not being hit at all, blocked by a firewall.

From the error, it looks like you're hitting a back-end that isn't configured for that request-type.

See these questions for a potential solution, assuming you control the back-end too.

Does tomcat support http PATCH method?

How do I stop Apache httpd from rejecting HTTP PATCH requests?

If you do control the back-end, but the above doesn't help, make sure that your controller function supports that request method. In Spring, for example, you have to declare that explicitly:

@Controller
MyController {

   @Requestmapping(value = "/api/patchTheThing", method=RequestMethod.PATCH)
   @ResponseBody String patchTheThing(....) {
        ...
   }
}


回答2:

Just set up an endpoint on a server of your choice and use your web server configure or coding language of your choice to issue a 501 response. But the problem seems pretty clear, the server is not expecting a PATCH request. If you had some networking problem you would not be getting a response at all.

you should strongly consider making sure your JavaScript code handles both happy path / success outcome as well as other types off sever response outcomes so your application can better handle how it wants to recover from such errors.