XMLHttpRequest Catch Empty XML Response with Status 200 - javascript

I have a script that queries a local PHP file by creating an XMLHttpRequest. Sometimes the PHP file returns nothing and thus an error is thrown saying:
XML Parsing Error: no root element found
Location: <URL of page>
Line Number 1, Column 1:
^
How can I catch this error so I can display a message saying something like, "No Results"?
This may be irrelevant for this question, but extra information probably won't hurt. I am using the Amazon Product Advertising API, and I only get this error when there are spaces in the keywords, even though I urlencode the keywords properly. It works fine if I only have one word, but not if there are multiple for some reason. Not quite sure what the issue is there, but I still would like to be able to catch these errors in a user friendly way.

Related

UnparseableJsonResponse for one specific, valid JSON

I have a standard Dialogflow agent, using javascript/node.js webhooks. It works perfectly well in most cases. I have recently encountered a problem which has me at a complete loss. I am currently saving some JSON-objects in conv.data to minimize the external API-calls my webhook have to make. For one specific JSON-object, fetched from an external API using node-fetch, the response I send from my side looks perfectly ordinary. I use firebase and the firebase logs do not show any error messages or any sign that there might be a problem. But I get this error in the Google Actions console:
UnparseableJsonResponse API Version 2: Failed to parse JSON response string with 'INVALID_ARGUMENT' error: "Parsing terminated before end of input. 8,\\"3\\":12},\\"w ^".
And in the stackdriver logs, the received response does not start with the usual
Received response from agent with body: HTTP/1.1 200 OK Server: ... etc
Instead it starts in the middle of the external API-JSON-file
Received response from agent with body: 8,\\"3\\":12},\\"winPercentage\\":1392}}}}, ... etc
This does not happen the first time the agent responds after fetching the JSON from the external API. The second time the agent responds after fetching the JSON, everything crashes regardless of whether the information from the JSON is used by that second call, regardless of anything at all except if the JSON file is overwritten between first and second call. If the file is overwritten the program runs perfectly. So the problem is likely part of storing and/or parsing this specific JSON file. Unfortunately the API I use in this application is not a public one and due to NDAs I cannot give any access to that JSON, so I understand that it is probably impossible for you to help me. I will however give as much information about the JSON as I can, and hope for the best:
It is valid according to https://codebeautify.org/jsonvalidator and jsonlint.com
It is structured the exact same way as other JSON files from the same API which do not crash the application
It is slightly larger that other JSON files from the same API. It has around 340 000 characters, others are around 280-300 000.
All JSONs, this as well as those that work, is from a Swedish company, therefore unusual characters like å, ä and ö are likely present.
The error message is always the same, except the start of the response is in different places in the JSON file. "8,\\"3\\":12}, ...", "ostPosition\\":2 ...", "3804,\\"startPoints\\":2960 ..." are some examples.
I am extremely grateful for any and all help I might receive, even if it's just what questions I need to ask, or where I might try troubleshooting next.
I suspect the problem is that the JSON you're trying to save is larger than the buffer size they allocate for conv.data, although I can't find any documentation to say there is some specific limit.
I'd check to see where the strings you're seeing in the error header are located in the JSON and try to keep it well under that limit.

How can I handle the 404 error thrown by making an XMLHttpRequest to an invalid URL?

I'm writing code where I use a typical XMLHttpRequest to make API calls using user input. Sometimes, the user input is such that the API call made is to an invalid URL (to be more specific, the API is a thesaurus and when you use it to ask for a word not in the thesaurus, you just get a 404 error and the page doesn't exist). This is giving a 404 error (and then a CORS error that I think is just a side-effect of the original), and citing the request.send() line. My problem is that whatever I try, I cannot seem to find a way to handle the 404 error.
I' ve tried to catch the error and handle it in various parts of the code, but in each one the error is thrown and not handled. Places I've tried to handle the error:
an "error" event listener. The callback is called, but the error has seemingly already been thrown and not handled
In the "load" event listener
the onreadystatechange function
Putting the request.send() call in a try/catch block and making the call synchronous; like with the error event listener, the catch code is run but the error is still not handled and makes its way to the console. Note that this is the answer suggested by How to catch the error thrown by an invalid URL using XMLHttpRequest with a similar title, hence why I've made a new thread.
How can I properly handle this error so it won't be sent to console?
My code looks like (without most of the bulleted past attempts above):
var req = new XMLHttpRequest();
req.open("GET",url, false);
req.addEventListener("load", function(event) {
... (handle response)
}
req.send(); //this is where the error comes in
Answering my own question with content from Jaromanda X's comments.
"The console shows network responses, and there's nothing you can do to hide that from an end user," so as long as I'm making a request that leads to a 404 error, I cannot get it out of the console. Given that in my example I don't see a way around sometimes making 404 requests (because the request needs to be made to check if the thesaurus has a word in it, and if it does not a 404 will occur), there is no fix for this problem (and there is no need to fix it).

Videojs how to get ErrorCode?

I am currently trying to get the error code from a Video.js error. I know how to get the error Message but I can't figure out how to get the numeric code for the error.
According to the documentation for MediaError there is a status property which is an array (at the bottom of the page). So it could contain multiple codes.
status: Array
An optional status code that can be set by plugins to allow even more detail about the error. For example a plugin might provide a specific HTTP status code and an error message for that code. Then when the plugin gets that error this class will know how to display an error message for it. This allows a custom message to show up on the Player error overlay.
So there's no guarantee there will even be a status code, the status array could be empty. However, you can check the length of the array to see if there are entries, then loop over them looking to see if they contain the status code(s) you're concerned with.

queryMySQL.php?query=myquery returns 403 forbidden error sometime

I have created a web site where in one page I select search criteria for mysql.
Depending on the drop-down elements selected, I create a string that I call myquery in a javascript, then I use
window.location.href = "queryMySQL.php?query=" + myquery;
and call a different page.
This works sometimes, but sometimes it gives me the 403 error and the page shows:
You don't have permission to access queryMySQL.php on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
I cannot figure out why it works sometimes and sometimes it does not, the syntax of the query is not a problem, I can get this error even if I remove the code on the page.
Additionally, this worked fine on another web hosting site, but when I copied this implementation on a different site I started having problems.
Suggestions?
EDIT ******************************************************
As I said this has nothing to do with the query. The target page can be a blank html page, and the error is still there. It looks like some security issue on this web hosting site because it worked fine on the other one and on my own server.
Try:
window.location.href = "queryMySQL.php?query=" + encodeURIComponent(myquery);
The query probably contains special characters that need to be encoded in a URL.

Unable to consistently load large json response using jquery.ajax

Recently I started facing issue with one of my scripts that loads a json response from the server. I am using jquery.ajax() to make an ajax call. The code snippet is so -
var request = $.ajax({
url: "script.jsp",
type: "POST",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response, error) {
console.log(response, error);
}
});
As I mentioned this script worked as recent as yesterday. I have not made any changes to either the server-side code or the front-end code. The json response is a bit large ~1 MB in size. But I validated the json output using -
python -mjson.tool < output.json
It prints out properly. Curious thing is FF & Chrome handle it differently.
In FF, I open firebug and see the ajax request being made. I see that the request is served in around 300ms but the loading wheel next to the link in the console is still animating for aorund 20 seconds. And after that the json response is properly processed and the result can be seen on the page. In IE also similar behavior, proper processing of the json after 20 seconds.
In Chrome, nothing happens for around 20 seconds after which I see an error in the console saying either "error": undefined or Failed to load resource. Alternatively it also prints the below stacktrace -
POST script.jsp
f.support.ajax.f.ajaxTransport.sendjquery.min.js:4
f.extend.ajaxjquery.min.js:4
DataTableWidget.extend._fetchBuildingBlockItemsPermissionBBItemsWidget.js:91
(anonymous function)PermissionBBItemsWidget.js:83
e.extend.eachjquery.min.js:2
DataTableWidget.extend._loadDataPermissionBBItemsWidget.js:82
DataTableWidget.extend.showPermissionBBItemsWidget.js:15
(anonymous function)permission-building-blocks.html:451
xLAB.min.js:5
ULAB.min.js:5
jLAB.min.js:5
ILAB.min.js:5
eLAB.min.js:5
a.onload.a.onreadystatechange
I dont understand this weird behavior in different browsers.
So in essence I made sure that -
Server side code returns the response fast. I put in some debug statements and saw the server log. None of the response form server take more than 500ms.
Made sure than json is properly validated. The fact that after 20 secs it is processed in both IE & FF without any issues is a proof of that. In addition to use of python's json.tool.
Set the dataType to json
So any pointers on the issue will be a great help. Thanks.
UPDATE
One more curious thing I noticed. While the request is being processed and I hit the refresh button even within 3 seconds of the original request, the process immediately completes. As in I see changes in the view of course fraction of a second later the page is wiped out due to refresh event.
UPDATE 2
I have noticed that after I slice up my big response by alphabets. The issue of looong response happens in only certain responses. I ran this split long response files through http://jsonformatter.curiousconcept.com/#jsonformatter and although it immediately returns saying that the josn is valid, it takes 20+ seconds to actually pretty print the response. I think the problem is happening due to certain characters like \u0026 so with this added info, how to resolve the problem? Here is the snipet of the problematic json.
I figured out the problem. The issue was with how the server-side code provided the client-side code JavaScript with the json string.
I was using a legacy method in our code base which actually rendered the already json string in a jsp page before passing it to the client. This was somehow screwing up the response. Also response type was text/html because of this.
As soon as I switched the response to be of actual application/json MIME type stream, everything was fine.
does your JSON have line feeds? Do you have Firebug or something line that open? The browser may be loading the JSON just fine, it might be your debugging tools crapping out. I Recall having issues before with inspecting certain JSON strings with certain tools just because it didn't have line feeds (or line feeds as understood in Windows). I'm wondering if the fact your logging the whole thing to the console doesn't have something to do with it.

Categories