Catch CORS error - javascript

I'm trying to load a CORS-disabled image, and get the error:
Cross-origin image load denied by Cross-Origin Resource Sharing policy.
I've tried catching the error as follows, but that obviously will not work.
How can I catch CORS errors after setting the .src property of an image?

Use the onError event.
if(image.addEventListener) {
image.addEventListener('error', function (e) {
e.preventDefault(); // Prevent error from getting thrown
// Handle error here
});
} else {
// Old IE uses .attachEvent instead
image.attachEvent('onerror', function (e) {
// Handle error here
return false; // Prevent propagation
});
}
Code should probably be consolidated so you don't have to write your code twice, but hopefully you've got the idea.

Related

How should i catch and handle 406 error in VUEJS

I have a route where i send to the api the day and h to verify in database if there is an opening in a schedule, if is not the api is sending 406. And i'm getting in console 406 error.
How should i handle that error to have a clean console?
You can simply wrap an api call into try-catch and simply don't to do anything with e in catch part.
try { ... you code here ... } catch(e){}
If you are using Axios for API calls you can create a global interceptor and return a response based on your status code to your component.
This would go in your main.js.
axios.interceptors.response.use(null, function(error) {
console.log(error);
if(err.response.status === 406){
//your code here.
}
return Promise.reject(error);
});
you can wrap your call in a try{} catch(e) {} to handle what happens after the error happens
but it is impossible to prevent the browser from showing the error in the console programmatically because of the potential risk that a script might misuse the errored requests to hide its activities from the user.
check_time(day,hour){
var fields = {};
fields.day = parseInt(day);
fields.hour = parseInt(hour);
try {
this.$http.post('courses/check', fields)
} catch {
this.$store.dispatch('alert', {'message': 'Already exist a course in this interval.'});
}
}

videojs - How to catch custom http error codes during live stream?

I have a live stream (HLS) that I am playing using videojs 6.8. For some users, after the playback has started (about 4-5 .ts files have been loaded) the server throws me a 409 error.
How do I catch this specific error code so that I can programmatically stop the playback and show an error message?
Currently, videojs keeps trying to resume playback indefinitely. I have tried retryplaylist, blacklistplaylist but all the info I get is that the playlist has been blacklisted and is being retried, I do not see the HTTP code anywhere in my console.log(). player.on('error') doesn't throw any error. I have tried all three of the following but none of them gives me the http code:
player.on('error', function (e) {
// no log
console.log(e);
})
player.tech().on('retryplaylist', function (e, data) {
// logs that it is being retried, but no http code
console.log('retry');
console.log(e);
})
player.tech().on('usage', function (e, data) {
// logs the even 'retryplaylist` but does not give me a http code.
console.log('usage');
console.log(e)
})
I do not want to put my message in retryplaylist because that event will be thrown in case of a slow network too (I already tested this).
What do I have to do to catch the specific 409 error?
Look like:
var retries = 0;
player.tech().on('retryplaylist', function (e, data) {
retries++;
if (retries >= 3) {
// do something
}
})

what is the xhr error event object details in this scenario?

I'm testing a simple mobile upload solution - this question is not about the actual upload - in chrome it uploads the pic in firefox the error event fires - so far so good - but now I need why it fires. The event is sent over so surely there is some error info in the object - but I check the spec on the progressevent which I kinda figured out it is sending but I still cant get a error code, description or anything to help me debug - any pointers please?
xhr.addEventListener("error", uploadFailed, false);
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
alert(evt.error.toString()); // this is where the trouble starts
// the evt.error is undefined?
}
thnx ;-)
XMLHttpRequest objects have the status or the statusText properties that correspond to the HTTP status of the request. That might be a good starting point. Also checking the JS console and the network tab in the debugger might yield some useful information (especially with CORS issues).
Using the status property, your error handler might look somehow like this:
xhr.addEventListener('error', function ()
{
if (xhr.status >= 500)
{
alert("Something went wrong on the server!");
}
else if (xhr.status >= 400)
{
alert("Something went wrong with the request on our side!");
}
else
{
alert("No HTTP error indicated, yet the error event fired?!");
}
});

vue-resource: catch "Uncaught (in promise)" when intercepting an ajax error

I'm using vue-resource to fetch data from the server. A user needs to have a JWT token to get the correct data. If the token is invalid or expired, a 401 status is returned. If the user tries to access a forbidden page, a 403 is returned.
I would like to catch those errors and handle them appropriately (globally). This means, that the calls should be completely handled by the interceptor (if 401, 403).
How can I prevent the browser message "Uncaught (in promise)" and create some global error handling? I don't want to have a local error handler on every call.
I have the following interceptor:
Vue.http.interceptors.push(function (request, next) {
request.headers.set('Authorization', Auth.getAuthHeader());
next(function (response) {
if (response.status === 401 || response.status === 403) {
console.log('You are not logged in or do not have the rights to access this site.');
}
});
});
And the following call in the Vue methods:
methods: {
user: function () {
this.$http.get('http://localhost:8080/auth/user').then(function (response) {
console.log(response);
});
}
}
This is a bit of a dilemma, isn't it. You don't want unhandled promise rejections to get swallowed, because it means your application might not function and you won't know why, and will never get a report of the error happening.
On the other hand, it's silly to use the exact same error handling mechanism for every single .catch() statement in your application, so implementing a global error handler is definitely the way to go.
The problem is that in most cases, you will have to re-throw the error from your global error handler, because otherwise your application will think the request went through ok and will proceed to process the data, which will not exist.
But this leads to the situation where the Uncaught (in promise) error shows up, because the browser will think you didn't handle the error, whereas in reality you did, in your global error handler.
To get around this, there is now the onunhandledrejection event, and you can use that to prevent the browser from logging these errors, but then you have to make sure you process them yourself.
So what we often do is have our own error classes, and when a response error is thrown, we convert the error to one of our error classes, depending on the HTTP status code.
We also append a property to this error, something like ignoreUnhandledRejection and set it to true. Then, you can use the global handler to filter out those errors and ignore them, because you know that you have already handled them globally:
/**
* Prevent logging already processed unhandled rejection in console
*/
window.addEventListener('unhandledrejection', event => {
if (event.reason && event.reason.ignoreUnhandledRejection) {
event.preventDefault();
}
});

How to handle can-connect errors correcly when connecting to a RESTful API

I've managed to load data and to save data. But cannot understand the error handling scheme needed.
When everything goes fine I receive the same object in that was sent but with an extra attribute _saving (false).
When something goes wrong, for instance try to store a string instead of a number, I'll get:
Bad request (error on the console, don't want that)
The response object (might be usefull to show an error)
"Uncaught (in promise)" error
Example:
Code:
this.save()
.then(function(result) {
console.log('ok1', result);
}).catch(function() {
console.log('errorHandler1');
});
OK:
Error:
I've been trying to use catch on promises, following this guidelines:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
but had no luck at all.
This should should work buy just changing p1.then to thisObjectThatIWantToSave.save.then but it didn't.
p1.then(function(value) {
console.log(value); // "Success!"
throw 'oh, no!';
}).catch(function(e) {
console.log(e); // "oh, no!"
}).then(function(){
console.log('after a catch the chain is restored');
}, function () {
console.log('Not fired due to the catch');
});
Again, it still stores the information when the data is correct, the problem I see is that I don't have the tools to decide when was the data correctly stored or not and to avoid triggering errors that can be correctly handled.
I'm using
canjs v3.0.0-pre.11
a restful API provided by feathers
Regarding the error handling ...
Bad request (error on the console, don't want that)
There's no way of preventing the error on the console. This is something chrome does.
The response object (might be usefull to show an error)
You can read the reason for the rejection in can-stache like {{promise.reason}}.
"Uncaught (in promise)" error
I'm not sure why this is being thrown as clearly, your catch is being hit. If you change it to:
this.save()
.then(function(result) {
console.log('ok1', result);
},function() {
console.log('errorHandler1');
});
Do you get the same behavior?

Categories

Resources