I am trying to load an image using the fromURL. The issue is that I'd like it to be able to load a default icon if it is not able to reach the Image server to download the image. Looking at the docs I did not see an error callback for the fromURL function. How are we supposed to catch that the call was not successful and therefore do the appropriate thing? It does not seem that the callback gets called at all when image load was unsuccessful.
You can use fabric.util.loadImage() method instead of fabric.Image.fromURL().
If you look at the fromURL() method implementation, internally it uses the loadImage().
The following code may help you:
fabric.util.loadImage('https://s3-eu-west-1.amazonaws.com/kienzle.dev.cors/img/image2.png', function(img) {
if(img == null) {
alert("Error!");
}else {
var image = new fabric.Image(img);
canvas.add(image).setActiveObject(image);
canvas.renderAll();
}
}, { crossOrigin: 'anonymous' });
Here is the fiddle: http://jsfiddle.net/k7moorthi/30kmn5kL/
once you have done the function, even if theres a mistake the callback keeps running, then you could check for the element (as other said) in this way:
let fabricBackgroundInstance = new fabric.Image.fromURL(imageToUse, (oImg) => {
if(oImg._element == null){
console.error('oImg', oImg._element);
return;
}
You could use getElement() to check this error.
fabric.Image.fromURL('/foo.jpg', (img) => {
if (img.getElement() === undefined) {
console.log('Failed to load image!');
return;
}
// do something on success
}
You can add the second argument isError to your callback function.
fabric.Image.fromURL("your image URL", (img, isError) => {
if (isError) {
console.log('Something Wrong with loading image');
return;
}
// do something on success
}
Also check fabric.js source code of Image.fromURL http://fabricjs.com/docs/fabric.js.html#line21471
Related
I have attached a screenshot of what I am trying to do. This is so basic yet so frustrating. I have to run a data parse after retrieving the array of objects from the first method being called but I can't add my method to the one inside ngOnInit or directly after it inside ngOnInit. Either way the method just simply doesn't run. Any ideas?
Image
ngOnInit() {
this.getSiteContent(this.route.snapshot.params['id']);
//Doesnt work
this.addUpdatedPages();
}
//in use
getSiteContent(id) {
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
});
//Doesn't show..
console.log('End of getSiteContent');
}
addUpdatedPages(){
//Doesn't show
console.log('Adding pages...');
for (var i = 0; i < this.siteContent.length; i++) {
this.checkNull(this.siteContent[i].SiteID, this.siteContent[i].SitePageID);
console.log(this.nullCheck[0].SiteID);
if (this.nullCheck.length > 0) {
this.siteContent[i].SitePageContent = this.nullCheck[0].SitePageContent;
}
}
}
Everything points to an unhandled exception when you call this.http.get. You should check your browsers console, that would show it if there was one. One likely reason is that http was not injected or is undefined.
ngOnInit() {
this.getSiteContent(this.route.snapshot.params['id']);
// if the above throws an exception anything below would not be called
this.addUpdatedPages();
}
getSiteContent(id) {
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
});
// If the call above to this.http.get throws an exception the code below would not be called
console.log('End of getSiteContent');
}
That being said the method addUpdatedPages should be called in the subscribe of the http.get because you want it to occur after the data base been retrieved. Modify the getSiteContent so that the line is moved into the callback for the observable's subscribe call.
this.http.get('/site-content/'+id).subscribe(data => {
this.siteContent = data;
this.addUpdatedPages();
});
I've read the feathersjs documentation, but after doing a find method in a service I realized that if I don't give any query parameters, the service returns all the data, which is something I don't want. How can I define a hook to validate that there are at least one query parameter in order to proceed; otherwise, send back a 403 error (bad request).?
I have doubts in the way to do it I tried this:
app.service('myService')
.before(function(hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
})
.find({
query: {
$sort: {
year: -1
}
}
})
And I tried in hook file on hooks this (that seemed really desperate & | stupid):
function noparams (hook) {
if (hook.params.query.name === undefined){
console.log('There is no name, throw an error!');
}
}
module.exports = {
before: {
find: [ noparams(this) ] ...
}
}
but it does not compile (I don't know what to send as a parameter there), and the examples seemed to be for pre 2.0 version and on top of that the code I found seemed to be in the app.js, but all is differently coded using feathers-cli, so the examples, even in the book, aren't against the scaffolded version, which is confusing because they shows the code in a different file were should be.
Thanks.
I ended using a before hook, so the code used is this:
const errors = require('feathers-errors');
module.exports = function () {
return function (hook) {
if(hook.method === 'find'){
if (hook.params.query.name === undefined || hook.params.query.length == 0){
throw new errors.BadRequest('Invalid Parameters');
}else{
return hook;
}
}
}
};
If have used feathers-cli to generate your application (feathers v2.x) you don't need to do anything else. If is an earlier version you maybe need to add the Express error handler and it is pointed out in the documentation|Errors|REST.
Thanks.
Followup from this question > Stopping response if document isn't found since it was recommended I use Promise.
So basic premise, I want node to return "Can't find ID" message if we can't find the id in our database.
v1.post("/", function(req, res) {
// If the project_id isn't provided, return with an error.
if ( !("project_id" in req.body) ) {
return res.send("You need to provide Project ID");
}
// Check if the Project ID is in the file.
helper.documentExists( ProjectsData, {project_id: req.body.project_id} )
.then(function(c) {
if ( c == 0 ) {
return res.send("The provided Project Id does not exist in our database.");
} else {
var gameDataObj = req.body;
GameData.addGameId(gameDataObj, function (err, doc) {
if (err) {
if (err.name == "ValidationError") {
return res.send("Please send all the required details.");
}
throw err;
};
res.json(doc);
})
};
});
});
And helper.documentExists
module.exports = {
documentExists: function(collection, query) {
return collection.count( query ).exec();
},
};
But the script continues to run after this and prints the "required data not found".
Output:
required data not found
1
I am using native ES6 Promises.
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
EDIT: Included the entire get route. (will fix those throw err later)
#######POINT 1#########
ProjectsData.count( {project_id: req.body.project_id} )
.then(function(c) {
#######POINT 3#########
if ( c == 0 ) {
console.log("1");
return res.send("The provided Project Id does not exist in our database.");
console.log("2");
}
});
#######POINT 2#########
//some other logic
console.log("required data not found");
Following async workflow: after POINT 1, the promise is created and your handler is attached. Now POINT 2 will continue, while (at some future clock the promise is resolved and you reach POINT 3.
With my limited understanding of your workflow/purpose I'd say simply put POINT 2 code in the else{} of the if at POINT 3 (as you rightly guessed in the comments).
EDIT: thanks to #jfriend00 for pointing out a serious mistake in the previous version of my answer.
Your code essentially results in this:
ProjectsData.count().then(...);
console.log("required data not found");
So, of course the second console.log() is going to run and print. Nothing that happens in the .then() handler runs until long after the console.log() has already run. And, even then, it can't stop other code from running. Promises don't make the interpreter "wait". They just provide structure for you to coordinate your asynchronous operations.
If you want to branch with promises, then you have to branch inside the .then() handler, not after it.
You don't show enough of the rest of what you're doing to know how to recommend a complete solution. We need to see the rest of your request in order to help you with the proper branching based on asynchronous results.
You probably need something like this:
ProjectsData.count( {project_id: req.body.project_id} ).then(function(c) {
if ( c == 0 ) {
return res.send("The provided Project Id does not exist in our database.");
} else {
// put other logic here
}
}).catch(function(err) {
// handle error here
});
I am using the following node module for validation: https://github.com/chriso/node-validator
Now, suppose I want to check on an user input like this check('abc').isInt(); I noticed that it basically throws an error!
I am pretty new with node.js but it seems to me that having to use try{}catch(e){} blocks every time I need to check on a user input is a bit on an overkill.
wouldn't it make more sense to have something like
if (check('abc').isInt()) {
// Do things here
next(null, stuff_I_want_to_return)
} else next(error);
instead of
try{
check('abc').isInt()
next(null, stuff_I_want_to_return)
} catch(e) { next(e); }
?? I have no idea, please clarify on what is the best approach to have in this case. Thanks in advance.
Their docs say you can do this
var Validator = require('validator').Validator;
var v = new Validator();
v.error = function(msg) {
console.log('Fail');
}
v.check('abc').isInt(); //'Fail'
That way you won't have to do try catch
Check module core-util-is providing functions introduced in Node v0.12.
In your case, method isNumber would be helpful
It's still fairly common in Node.js for synchronous functions to throw as they don't usually have a callback to pass an error to. But, they still need some way to deliver it to calling code and return error; would generally be an unexpected choice.
Though, the documentation for node-validator does include an example for extending Validators with a getErrors() method under "Error Handling."
Validator.prototype.error = function (msg) {
this._errors.push(msg);
return this;
}
Validator.prototype.getErrors = function () {
return this._errors;
}
Which could be used to report errors without throw:
var validator = new Validator();
if (validator.check('abc').isInt()) {
next(null, ...);
} else {
next(validator.getErrors());
}
Note: The _errors property should already be defined after using .check().
In a Chrome extension, a script may be included as a content script or background script.
Most stuff it does is the same, but there are some would vary according to different context.
The question is, how could a script tell which context it is being run at?
Thank you.
I think this is a fairly robust version that worked in my initial tests and does not require a slower try catch, and it identifies at least the three primary contexts of a chrome extension, and should let you know if you are on the base page as well.
av = {};
av.Env = {
isChromeExt: function(){
return !!(window['chrome'] && window['chrome']['extension'])
},
getContext: function(){
var loc = window.location.href;
if(!!(window['chrome'] && window['chrome']['extension'])){
if(/^chrome/.test(loc)){
if(window == chrome.extension.getBackgroundPage()){
return 'background';
}else{
return 'extension';
}
}else if( /^https?/.test(loc) ){
return 'content';
}
}else{
return window.location.protocol.replace(':','');
}
}
};
Well I managed to work out this:
var scriptContext = function() {
try {
if (chrome.bookmarks) {
return "background";
}
else {
return "content";
}
}
catch (e) {
return "content";
}
}
It's because an exception would be thrown if the content script tries to access the chrome.* parts except chrome.extension.
Reference: http://code.google.com/chrome/extensions/content_scripts.html
The best solution I've found to this problem comes from over here.
const isBackground = () => location.protocol === 'chrome-extension:'
The background service worker at Manifest v3 does not contain a window.
I use this as part of my extension error handling which reloads the content scripts, when i receive an Extension context invalidated error:
...
if (!self.window) {
console.warn('Background error: \n', error);
} else {
location.reload();
}
...