I got a question regarding success/error
callbacks of the methods in Backbone.js. As I am new to this , my question might seem to be simple or something like that.
As far as I know, save()
or fetch()
methods of a model fires success
, if there is no error (say, exception) on the server. The question is, should I throw an exception on the server in order to get the type of an error on the client side? Let me give you an example of what I mean:
I have a UI on the web which creates a new user for the app, for instance. My client-side would look something like this:
var userView = Backbone.View.extend({
initialize:function(){ ... },
events: {
'click #sign_up': 'createAccount'
},
createAccount: function() {
login = $('#login').val();
password = $('#password').val();
var user = new User(); // User is a model
user.save({login: login, password: password},{
success: function(data) {
if (data != null) {
alert('success');
} else {
alert('fail');
}
},
error : function() {
alert('error');
}
}
});
Accordingly, server side would be:
@Controller
@RequestMapping("/users")
public class UsersController {
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody User createUser(@RequestBody User user) throws Exception {
if (user == null || !user.isValid()) {
return null;// not valid - error message 1
}
if (userDao.getUserByLogin(user.getLogin()) != null) {
return null;// such user already exists! - error message 2
}
userDao.saveUser(user);
return user;
}
What I want is being able to send proper error messages accordingly. If I return null
, then the data inside success
callback will be the model that I've just populated before send the request. If I throw an exception, then it will fire error
. At this point, what approach should I take to meet my needs.