Check whether url returns 404 - javascript

I'm trying to check whether an URL returns 404, 403 etc when including a Javascript file. It works ok, but I still get an error in "Chrome developer tools".
This is my code:
(function() {
try
{
var ml = document.createElement('script');
ml.type = 'text/javascript';
ml.async = true;
ml.id = 'monoloop_invoke';
ml.onerror = function(){alert('File does not exist');};
ml.src = 'http://somedomain.com/somefile.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ml, s);
}
catch(err)
{
alert('Error: '+err);
}
})
();
If the file does not exist it shows the error "File does not exist" from the ml.onerror function. This is all good. But the problem is that I still get an error line in my console like:
GET http://somedomain.com/somefile.js 403 (Forbidden)
and the try/catch does not catch this error.
Anyone knows how to solve this? Or is there another way of testing if a URL exists before including it? I cannot use AJAX as I need to use this in a cross-domain fashion. I could use jQuery if necessary.
EDIT: It does not show an error in IE, so i guess this maybe just relates to the way chrome reports issues. Does anyone see a more elegant solution for checking if a file exisists without genreting anything in the console.

jQuery.getScript( url, [ success(data, textStatus) ] )
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
url
A string containing the URL to which the request is sent.
success(data, textStatus)
A callback function that is executed if the request succeeds.
To catch the errors use the ajaxError event:
http://api.jquery.com/ajaxError/

Related

Handling error messages in browser console while using fetch

Problem:
I am seeing following error in my browser console, I don't want a solution to resolve this error.
I want a solution to remove from the browser console.
GET https://logo.clearbit.com/objectivepartners.com net::ERR_ABORTED 404
I came to following solution which can handle consoling but while using fetch
it is not working:
console.defaultError = console.error.bind(console);
console.errors = [];
console.error = function(){
if (!arguments[0].includes("404")) {
console.defaultError.apply(console, arguments);
}
console.errors.push(Array.from(arguments));
}
fetch("https://logo.clearbit.com/objectivepartners.com").then(response => {
if (response.ok) {
console.log("okay");
}
}).catch(error => {
console.error("404"); // WILL NOT SHOW IN BROUSER CONSOLE
console.error("error"); // WILL SHOW IN BROWSER CONSOLE
});
Here,
I want if arguments include 404 then do not console it in the browser.
But on the fetch request failure, it includes 404 still it consoling, that I do not want to be happening
could it be possible that when fetch fail i can disable using in this code (by changing) or any other way?
Unfortunately, I didn't find any solution to resolve at the client-side or using javascript.
But I resolve this by creating an endpoint to API side and giving URL to that API to check that URL is valid or not, based on API response I handled in fetch

How can I see the full server response for this API error message in Google Scripts?

I'm getting an error response from the API that I'm using, but Google scripts seems to truncate the message. How can I see the full message in Google scripts?
This is the message:
Request failed for https://api.myintervals.com/task/ returned code 400. Truncated server response: {"personid":"180761","status":"Bad Request","code":400,"error":{"code":18,"message":"Validation error has occurred (missing required field/paramet... (use muteHttpExceptions option to examine full response) (line 171, file "IntervalsPull")
Just as #DrSatan1 pointed in the comment, pass muteHttpExceptions option in the parameter to suppress the exception and get the error returned as HTTPResponse.
options = {muteHttpExceptions: true};
var response = UrlFetchApp.fetch("https://api.myintervals.com/task/", options);
Logger.log(response.getContentText());
Now view your logs to see the complete error response.
While setting response to logger or console works, even that will be truncated if the response is too long. You may have to set the response to Drive in such cases.
options.muteHttpExceptions = true;
const res = UrlFetchApp.fetch(url, options);
console.log(res.getResponseCode());
console.log(res);
DriveApp
.getFoldersByName('test'/*A folder in Drive*/)
.next()
.createFile(res.getBlob().setName('response'))

try catch on javaScript does not work

I have a code for reading a json file in JS. I had the code wrapped in "try catch" blocks.
The way I get it - if the file is not found for some reason, it should enter the "catch" block.
Yet, if "lang" is undefined - it throws a 404:
" GET --<-server->--/settings/Lang_undefined.json 404 (Not Found) "
without ever entering the "catch" block.
can anyone help me understand why it is so?
Thank you!!
function loadDic() {
try {
$.getJSON(SERVER_URL + "settings/Lang_" + lang + ".json", function(data) {
dic = data["dictionary"];
setLanguage();
});
} catch (err) {
return false;
}
}
Since you appear to be making an ajax request (not a jsonp request,) you can catch the error using the error callback.
function loadDic() {
$.getJSON(SERVER_URL + "settings/Lang_" + lang + ".json", function(data) {
dic = data["dictionary"];
setLanguage();
}).fail(setLanguageFail);
}
Ajax is asynchronous.
The getJSON function sends an HTTP request.
It sends it successfully
The try is successful
The Ajax then gets a response saying that the server had a 404 error
You haven't specified an error event handler, so nothing happens
The 404 error does not cause an exception to be thrown (it is an HTTP error, not a JavaScript error) and there is nothing waiting to catch an exception at that time anyway.
If you want to do something in the event of an error, then specify a function to handle it (you can't do this with getJSON(), you should use ajax() instead). Note that you cannot return (based on this) from the function that included the getJSON call.

Parse Json, error in the executing

I'm trying to execute a javascript request:
var s = document.createElement('script');
s.src = "https://api.instagram.com/v1/media/popular?client_id=" + client_id + "&count=12";
s.addEventListener( 'load', function(){ s.parentNode.removeChild(s); } );
(document.head||document.documentElement).appendChild(s);
console.log(s);
The console print:
<script src="https://api.instagram.com/v1/media/popular?client_id=myclientid&count=12"></script>
And this url, return me the json, is possible excecute this request?
And this url returns me json, is possible excecute this request?
The request is made, but when you attempt to execute a JSON file like a script it will fail with an error message. You are not allowed to access it either, because of the SOP.
You would need to make the api respond with a JSONP script to let your snippet work. Check instagram's documentation on this.

MooTools Request Failing

So I have a bit of a problem. When I ask MooTools to send a request it comes back as failed every time. I can't seem to diagnose the problem either because if I try to get the returned header info the console just gives me "Refused to get unsafe header 'Status'" Message. The only thing I can think of is that the server isn't letting me access outside resources but maybe I just coded it wrong.
Here's the request code:
var finfo = current.textFontData();
var url = 'http://antiradiant.com/clients/TMW/rbwizard/mailer.php?s='+current.size+'&b='+current.box+'&l='+current.lidWood+'&c='+current.cartID+'&f='+finfo.font+'&l1='+finfo.line1+'&l2='+finfo.line2;
console.log(url);
var req = new Request({
url: url,
onSuccess: function() {
console.log('success');
//atc2.send();
},
onFailure: function() {
console.log('failure');
console.log(this.getHeader('Status'));
//atc2.send();
},
onException: function(headerName, value) {
console.log('exception');
console.log(headerName+': '+value);
}
});
req.send();
This code is derived from the resource rb_wizard.js (lines 81-103) on http://tylermorriswoodworking.myshopify.com/pages/recipe-box-wizard?b=maple&l=cherry&s=3x5&c=42042892
Mootools has a class called Request.JSONP that will help with your cross domain problem. Its sub class of the Request class, so your methods should work the same. I believe you need to call .post() or .get() at the end instead of send, but thats about all that should chnge. I'm not sure what version you're running on but here is the link tot he docs Mootools Request.JSONP
The error message "Refused to get unsafe header 'Status'" is spat out by WebKit based browsers (Safari, Chrome, etc) when you violate the cross-domain security model.
Therefore, it seems likely that the code you pasted is located on a domain other than antiradiant.com, and therefore is not allowed (by the browser) to request sites on antiradiant.com.
What I ended up doing was just using an iframe. All I really had to do was send data to another site and not receive any so it worked out.

Categories