How do I get the error messages in Backbone.js?

2019-05-04 10:40发布

问题:

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.

回答1:

You should not throw an exception. Well you can but then you should handle the exception on the server-side and only return correct HTTP codes.

e.g.

If a user is not found on the server side, normally you return a 404 HTTP Status Code. 404 will fire the error callback.

The error call back has multiple arguments in case you want to pass some data on the server (like error message). According to docs:

"error" (model, xhr, options) — when a model's save call fails on the server.

You can access the error message in xhr object.