Backbone.js Error Handling - how do you do it?

2019-01-31 17:22发布

问题:

I'm wondering how people typically do error handling with backbone.js. It would be nice for something to popup everytime I call model.save (which in turn calls Backbone.sync). The thing is, how does backbone.js know when an error or a success has occurred on the server? I understand it would know if there was a 500 server error or something like that (which jquery knows about since Backbone.sync calls jQuery.ajax) - but I want to be able to pass messages and other codes so I can give more meaningful error messages to the user.

I have one idea and would love some feedback. The idea is to override Backbone.sync. The new sync gets a response from the server, which must be in a particular format. This format would be something like:

ServerResponseObject:
  > ResponseCode
  > Message
  > Model

Nothing fancy, but basically, instead of just returning the plain model, it is wrapped up with a ResponseCode and Message which can be shown to the user.

Is this the normal way to do it? Any other approach that is better?

Thanks!

回答1:

In my ears this sounds a bit on the complex side, at least to start with. Backbone.sync will already report errors that you can catch in your models .save() method:

this.mymodel.save(/* ... */, {success: function(model, result, xhr)...,
                              error: function(model, xhr, options)...}

(docs).

If your serverside follows HTTP specs well, the error code is already provided (500 - server error, 404 - model not found, you know..), and even if the server sends an error code it can still send content (perfect for your message). So you basically already have all parameters built in to the HTTP protocol itself. In my experience you get to write less code if you work with the protocol instead of building new layers on top of it.

In your errorcallback above, you probably have good possibilities to call the rest of your system and post an error to some application message bus or similar (via Backbones own event mechanism or some dedicated library).



回答2:

We switched to sending back the standard format JSend a while back. It's basically just a JSON wrapper around the response that has provisions for messages and error codes to come back in addition to the data you expect.

The main reason we had to do it was because we had services which were responding with 400 errors when it was really not the appropriate thing. The client didn't have malformed syntax or any protocol level errors at all, there was just some problem with something where we needed a more nuanced response and that gave it to us. After we did that everybody ended up much happier on both the client and server sides.



标签: backbone.js