Parsing a JSONP response in Javascript with a 4xx or 5xx Http error code

I am implementing an application that relies on communication between a JavaScript client and a server that knows how to respond to the client using JSONP notation.

I am trying to handle a case in my Javascript client where my server is returning with a status code of http 4xx or 5xx. Currently, I see that the script is not being evaluated, because the browser believes that this is an error (as it is.) However, I still want to read what my server should say in this case 4xx or 5xx in my JavaScript client.

I see that this is causing an error in the script tag element, but I am concerned that this is not a cross browser and will not be a reliable solution.

Did anyone still manage to parse the jsonp response, even if the http status code is 4xx or 5xx?

I am starting to believe that I should just use this “set timeout” solution, which “detects” a failure by indicating the callback function to the jsonp request, will be completed within a certain period of time, and if it is not, an error has occurred.

EDIT: I temporarily return a 200 status code when my server detects a jsonp client and then tunnels the error message / status in the returned json object. I was hoping to use HTTP status codes, but I think this is not for the javscript client.

+6
javascript jsonp
source share
3 answers

One approach when using JSONP is to embed status information in a callback. So the signature of the callback function will look like

callback(result, status, message) 

So, if your call looks like

 http://myurl.com/?callback=fn 

generate code for a successful call that looks like

 fn({"data":"my great data"}, 200) 

and for an exceptional condition

 fn(null, 500, "server error"} 
+7
source

JSONP is a cross domain problem. When it works, it works well. But when it’s not, you have no way to find out what went wrong.

setTimeout is another hack on top of the original. If you must use JSONP and still need to detect errors (no processing), this is what you will need to do. There is no better solution.

If you are managing a server, try using alternatives such as Cross-Origin-Resource-Sharing (CORS) or Flash crossdomain.xml to allow cross-domain requests. If you do not control the server, you can proxy the response through your server to get better control.

+8
source

You can check the status of the XHR object (if you are not using the JS library).

 if(xhr.readyState == 4){ if(xhr.status == 200){ // good }else if(xhr.status == 502){ // d'oh } } 

If you use jQuery, you can pass statusCode to handle special cases for $. ajax

-3
source

All Articles