I am using the 2.3.1.min version of the jquery-jsonp library found here: https://github.com/jaubourg/jquery-jsonp and it works as expected, namely the error function fires when an error occurs. However, I cannot to seem to display the error encountered. I checked the docs on github project but could not find an answer.
Is this a limitation? Or am I not calling the right object?
My implementation..
The url parameter below is set to return a 404 page on purpose. Chrome dev tools shows a 404 response, but I cannot seem to capture that result..
<script type="text/javascript">
$.jsonp({
url: 'http://apps.mydomain.com/Service/NonExistant?&max=4&format=json',
callbackParameter: "callback",
error: function(xOptions, textStatus){
// this lines returns "error"
console.log(textStatus);
// this returns the Object (but expanding it reveals no indication of error code / message)
console.log(xOptions);
},
success: function(json, textStatus) {
Populate(json); // this works fine
}
});
</script>
Sadly, you can't. Johnny Wey explains it far better than I could - but essentially, it's relying on a "script" tag to get the JSON response, rather than a request executed via javascript.
You could wrap the type of error within the JSONP response per Parsing JSONP Response in Javascript when 4xx or 5xx Http Error Code is Present, but that still won't help you with a 404 error.
Unfortunately, though JSONP error handling is effectively non-existent. The "Cautionary Note" from IBM specifically mentions that "First and foremost, there is no error handling for JSONP calls".
Related
I have a Laravel application with Vue js and until a while ago it was working perfectly. Now when I go to any page that uses Vue js this error appears: [Vue warn]: Error in render: "SyntaxError: Unexpected token u in JSON at position 0".
When I reload the page by clearing the cache (Control + Shift + R on Mac OS) it works again, but when I update without this command the error appears again.
PS: I didn't do any package updates for both laravel and npm, it just stopped working out of nowhere.
Try this in the console:
JSON.parse(undefined)
Here is what you will get:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at <anonymous>:1:6
In other words, your app is attempting to parse undefined, which is not valid JSON.
There are two common causes for this. The first is that you may be referencing a non-existent property (or even a non-existent variable if not in strict mode).
window.foobar = '{"some":"data"}';
JSON.parse(window.foobarn) // oops, misspelled!
The second common cause is failure to receive the JSON in the first place, which could be caused by client side scripts that ignore errors and send a request when they shouldn't.
Make sure both your server-side and client-side scripts are running in strict mode and lint them using ESLint. This will give you pretty good confidence that there are no typos.
Sometime it is becaseu of this let data = JSON.parse(this.response); so try to change it to
let data = JSON.parse(this.responseText);
I really did was change this.response to this.responseText
I am attempting a post action using Ember-Data, and getting the following error which seems pretty common:
Error: The adapter rejected the commit because it was invalid
Problem is, seems like usually this returns more specific errors; I am only seeing the above message and a generic 422 error from the browser.
Does anyone know what I can do to access any specific error messages that might be thrown?
Potentially relevant info:
Using jsonapify on an express server to write to MongoDB
router.post('/',
jsonapify.create('info'),
logger.logErrors(), jsonapify.errorHandler()
);
I would expect the following code to log some sort of response but I am never able to see the message in this console.log:
info.save().then((response)=> {
console.log(`Server responded with ${response}`);
});
Sorry for the vagueness here, I'm sure there could be all sorts of problems with my models and whatnot, but I want to know what I can do to find the more specific errors if they exist.
Thanks much and plz lmk if I can update with more info.
.then() takes two arguments, like so: .then(success, failure) the first one being a function to be called on success, and the second to be called on failure. A 422 response is a failure, and your current code only has a success handler, so it will never be called. Basically, copy-paste your current success handler to be the second argument to your .then() call.
Also, generally in your browser you can open up the inspector and take a look at the request in the 'network' tab.
Your new debugging code could look something like this:
let success = (response) => {
console.log(`Server responded with ${response}`);
};
let failure = (response) => {
debugger;
};
info.save().then(success, failure);
Then you should be able to poke around the response object in your js console and see what's going wrong.
How to handle urlfetch error? I'am trying muteHttpExceptions: true, but it doesn't work and the script breaks.
function myFunction() {
var result = UrlFetchApp.fetch("http://www.soccer-wallpapers.net/soccer_wallpaper/barcelona_fc_barcelona_360.jpg ", {
muteHttpExceptions: true });
Logger.log("code: " + result.getResponseCode());
Logger.log("text: " + result.getContentText());
}
But I'm trying another error url to work fine.
http://img8.uploadhouse.com/fileuploads/2058/20586362b34151eb10a4001e1c44305fe41bff6.jpg
Solved handle using the try and catch method.
try
{
var page = UrlFetchApp.fetch("http://www.soccer-wallpapers.net/soccer_wallpaper/barcelona_fc_barcelona_360.jpg");
}
catch(err)
{
Browser.msgBox("error");
}
}
This seems to be working as designed. The muteHttpExeptions is for doing just that. It tells the script to carry on as normal if it received an HTTP error status. In your first example code, the error is not an HTTP error. There is no web server to return an HTTP code of any type. The URL does not exist. The service that reaches out to the internet cannot continue, and there is no HTTP exception to be had.
When I visit http://www.soccer-wallpapers.net/soccer_wallpaper/barcelona_fc_barcelona_360.jpg, I get a timeout message. There was nothing to respond to my request. It appears that soccer-wallpapers.net is no longer responding to requests. It does have a DNS entry, but does not respond to ping from my location.
If you must handle bad URLs, potentially down servers and other server errors, then you will need to use a try{}catch(){} block. How you handle those errors is up you. The muteHttpExceptions flag is meant more for handling HTTP errors as part of your application instead of throwing errors at the script level.
That's still remains an issue in functions that are called in cells where the try-catch in this case is just ignored
I have an application uses Spring Security 3(has a Jackson Marshaller) runs on a Tomcat 7. I designed my application with Jquery and it runs well. I designed a login page with Ext JS and after successful login it redirects to index.html. However it gives an error and can't redirect because when server sends HTML file it comes into that function at Ext JS:
Ext.util.JSON = new (function(){
...
doDecode = function(json){
return eval("(" + json + ")");
},
...
I wants to render it as a JSON response and gives an error as usual. How to solve it?
PS: It gives that on Firebug:
syntax error
[Break On This Error] (<!DOCTYPE html>
The server is not returning valid JSON. Its look as if it is returning a HTML page (perhaps a friendly error page). If you follow the stack trace up its probably Ext.decode response.responseText (inspect this you'll see whats returned although not the best way)
First step would be to investigate the request in the Net panel in Firebug or Chrome, look at the request and response headers and content this will point you in the right direction. Please please please do not resolve this problem without first learning to use a client side browser debugger (Firebug or Chrome Dev Tools or even Safari) such as walking the stack on break on error, break on XHR, inspect the XHR headers and response etc.. not just watching the console window.
You might be able to fix this continuing blind but you'll pay heavily again next time.
Is possible to intercept 404 error without using web server (browsing html file in the filesystem) ?
I tried with some javascript, using an hidden iframe that preload the destination page and check for the result and then trigger a custom error or redirect to the correct page.
This work fine but is not good on perfomance.
A 404 error is an HTTP status response. So unless you are trying to retrieve this file using an HTTP request/response, you can't have a genuine 404 error. You can only mimic one in something like the way you suggest. Any "standard" way of handling a 404 error is dependent on your flavour of web server anyway...
404 is a HTTP response code, and as such only delivered through the HTTP protocol by servers that speak it. The file:// extension isn't a real protocol response as such, it's a hack built into clients (like browsers) that enable local file support, however it's up to browsers / clients themselves whether they expose any response codes from their file:// implementation. In theory they could report them in the DOM, for example, but they would be response codes exposed to themselves, and as such rarely implemented. Most don't, and there isn't a standard way for it. You may look into browser extensions, like Firefox, and see if they support it, but then, this is highly unstandard and will likely break if you pop it on the web.
Why don't you want to use the server?
I don't believe that it's possible to handle a 404 error client-side, because a 404 error is server-side.
Whenever you load a webpage, you make a request to the server. Thus, when you ask for a file that's not there, it's the server that handles the error. Regular HTML/CSS/JavaScript only come into the picture when the server sends back a response to tell you that it can't find the file.
Steve
Because I was looking for this today. You can now do this without a server by using a Service Worker to cache the custom 404 page, and then serve it when a fetch request status is 404. Following the instructions on the google cache lab, the worker files looks as follows:
const filesToCache = [
'/',
'404.html'
];
const staticCacheName = 'pages-cache-v1';
self.addEventListener('install', event => {
console.log('Attempting to install service worker and cache static assets');
event.waitUntil(
caches.open(staticCacheName).then(cache => {
return cache.addAll(filesToCache);
});
);
});
self.addEventListener('fetch', event => {
console.log('Fetch event for ', event.request.url);
event.respondWith(
caches.match(event.request).then(response => {
if (response) {
console.log('Found ', event.request.url, ' in cache');
return response;
}
console.log('Network request for ', event.request.url);
return fetch(event.request).then(response => {
console.log('response.status:', response.status);
// fetch request returned 404, serve custom 404 page
if (response.status === 404) {
return caches.match('404.html');
}
});
});
);
});