catch exception in angularJS - angularjs

I just went through an angular-fullstack application and i came across this piece of code:
catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
I understand the piece of code what it is trying to say but i want to know if suppose an error occur what exactly is passed to function(error, field). i unable to interpret what happens if error occurred. so that i'll able to know what is actually happening in this code
This piece of code is in a controller
Can anyone please explain the whole procedure with example?

Looks like you're "catching" errors (probably returned from a restful service) and mapping each error in the error array to it's specific field.
The validity of that field is then set to false, which is something held by the angular form.
Finally, there is some sort of binding to $scope.errors that displays each error message that is added to the $scope.errors array.
Looks like pretty simple and typical validation. It has nothing to do with core angular error handling and is simply a way to add validation information to the form/page.

Related

Calling getValidationErrors() with breezejs entity validation in angularjs ng-repeat causes errors

Let say we have a simple entity level validator like this:
function entityIdIsValidFn(entity,context) {
if (entity.Id1)
return true;
if (entity.Id2)
return true;
return false;
}
var entityIdValidator = new breeze.Validator("entityIdValidator", entityIdIsValidFn, { messageTemplate: "Id1 or Id2 must be defined" });
var entityType = manager.metadataStore.getEntityType("Entity");
entityType.validators.push(entityIdValidator);
Now if I try to display validation error messages in a angularjs view like this:
<div ng-repeat="error in selectedEntity.entityAspect.getValidationErrors() " class="alert alert-danger">{{error.errorMessage}}</div>
I get a bunch of Error: 10 $digest() iterations reached. Aborting! errors.
If I have validators only attached to properties validation errors will display just fine but once I attach avalidator to an entity type I run into trouble. Anybody got an idea why this happens and consequently how to display validation error messages correctly?
Any help would be much appreciated.
While I did not get your error I had no problem reproducing one of my own. There is a Breeze bug in getValidationErrors (line 3839 of breeze.debug.js v.1.4.6) where it iterates over the error collection, testing the property name.
ve.property.name === propertyName
An entity-level validation error (ve) does not have a property and therefore the code fails with a null reference error while trying to access the undefined property.name.
A temporary workaround might be to patch this line with
ve.property && ve.property.name === propertyName
We've fixed it in GitHub. It will appear in the next (1.4.7) release. Thanks for reporting it.

Backbone not sending PUT to server

I am having trouble with trying to get backbone to send a PUT request out to my rails server on save. I am not sure what I am doing wrong here, it is fine with GET requests just not PUT..
Here is the code that is in my view that I use to save my model.
e.preventDefault()
$(#el).find('#error_explanation').html ""
data = Backbone.Syphon.serialize(this)
setError = false
#model.set(data, error: (model, error) ->
setError = true
)
#model.save()
Any help would be greatly appreciated.
Thanks,
-do
Stupid me....
Here is what was in my model.
validate: ->
console.log "validating"
console.log "options: #{options}"
errors = []
if(!#.validateEmail(#.get('email')))
errors.push("Email can't be blank")
if(!#.validateName(#.get('first_name')))
errors.push("First name can't be blank")
if(!#.validateName(#.get('last_name')))
errors.push("Last name can't be blank")
return errors
This was actually being called when I was trying to save it which I was just trying to call manually. Since I wasn't returning the correct data saying that it was valid/invalid it just was always invalid.
ooops...
-do

Site wide error management with backbone

The problem
I want to have a default error handler in my app that handles all unexpected errors but some time (for example when saving a model) there are many errors that can be expected so I want to handle them in a custom way rather than show a generic error page.
My previous solution
My Backbone.sync function used to have this:
if(options.error)
options.error(response)
else
app.vent.trigger('api:error', response) # This is the global event channel
However, this no longer works since backbone always wraps the error function so it can trigger the error event on models.
New solution 1
I could overwrite the fetch and save methods on models and collections to wrap options.error and have the code above there but this feels kinda ugly.
New solution 2
Listen to error on models, this won't allow me to override the default error handler though.
New solution 3
Pass in a custom option to disable the global triggering of the errors, this feels redundant though.
Have I missed anything? Is there a recommended way of doing this?
I can add that I'm using the latest version from their git repo, not the latest from their home page.
Could you do this in your overridden sync? This seems to accomplish the same thing you did before.
// error is the error callback you passed to fetch, save, etc.
var error = options.error;
options.error = function(xhr) {
if (error) error(model, xhr, options);
// added line below.
// no error callback passed into sync.
else app.vent.trigger('api:error', xhr);
model.trigger('error', model, xhr, options);
};
This code is from Backbone source, I only add the else line.
EDIT:
This is not the prettiest solution, but might work for you. Create a new Model base class to use, instead of extending Backbone.Model, extend this.
var Model = Backbone.Model.extend({
// override fetch. Do something similar for save, destroy.
fetch: function(options){
options = options ? _.clone(options) : {};
var error = options.error;
options.error = function(model, resp) {
if (error) error(model, resp);
else app.vent.trigger('api:error', resp);
};
return Backbone.Model.prototype.fetch.apply(this, [options]);
},
});
var MyModel = Model.extend({});
var model = new MyModel();
model.fetch(); // error will trigger 'api:error'
Actually, this might be better than overriding sync anyways.
Possible alternative is to use this: http://api.jquery.com/ajaxError/.
But with that, you will get the error regardless of whether you passed in an error callback to backbone fetch/save/destroy.

BackboneJS model.fetch() unsuccessful

Hi I have this model :
window.shop = Backbone.Model.extend({
initialize: function () {
console.log('initializing shop');
},
urlRoot: "shopData.json",
});
and then i go :
var myShop = new shop();
myShop.fetch({
success: function (model, resp){
console.log(resp);
},
error: function (model, resp){
console.log("error retrieving model");
}}, {wait: true});
now I'm always getting the error message - never reaching success :-(
thanks for any help.
Edit 1:
As per your comment the server is sending the proper response but Backbone is still calling the error function. Add the following line at the beginning of the error callback:
error: function (model, resp){
console.log('error arguments: ', arguments);
console.log("error retrieving model");
}
The first line should print an array of objects. The first element in the array should the jqXhr object, the second should be a string representation of the error. If you click on the first object, the dev tools will let you inspect its properties. Read up on the properties of the object here http://api.jquery.com/jQuery.ajax/#jqXHR.
Using that information you can verify if the jQuery is receiving an error from the server.
If there is no server side error, then check the value of the responseText property. That holds the string data returned from the server. $.ajax will try to parse that data into JSON. Most likely the parsing is throwing an error and the error handler is being raised instead.
Copy the response text and paste it into http://jsonlint.com/. Verify that the response sent from the server is valid JSON. Do update your question with the output of the console.log statement and the responseText property of the jqxhr object.
-x-x-x-
You seem to be using the model independently. As the per the documentation, http://backbonejs.org/#Model-url,
Generates URLs of the form: "/[urlRoot]/id"
That means, you are making a request to shopData.json/id. Also, you haven't specified the id.
Insert a console.log(myShop.url()) before the myShop.fetch(). Let us know whats the output. Also, possibly share the details of the ajax request as seen in Firebug or Chrome Dev Tools. I am interested in two things, the request url and the response returned by the server. (http://getfirebug.com/network)

submit changes on extjs roweditor grid

I have a grid what update my database (via PHP) with JSON record.
I want to know, how the data writed - record or not. I have an answer from PHP (true or false) to the grid, but dont know how to use it. How my grid can use this answer? (success event?)
Now, for example, User added new record without id at database (and i need this id for the future update), php answer what record saved(true) and told me id of new record. How I should work with it?
And I saw somehere some beauty flowing from the top of screen windows - how do the called?
Sorry for typically questions, but I cant find answer for it.
Thanks.
If you are using Ext.Ajax.request to make the connection this is how you do it.
Ext.Ajax.request({
url: 'ajax_demo/sample.json',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
There is a success callback function you specify which gets the response from the server which is a JSON object. This is where you can send things back and then manipulate your roweditor grid however you like.
Success also doesn't mean that everything went ok, it just means the request did not produce an html error code 4xx or 5xx.
The failure callback function is what to do if the server returns an error code for the AJAX request.

Resources