Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

backbone.js

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!

like image 581
Nick Lang Avatar asked Nov 17 '11 03:11

Nick Lang


People also ask

How would you handle an error in JS?

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.

How does Backbone JS work?

BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications. When a model changes, it automatically updates the HTML of your application. BackboneJS is a simple library that helps in separating business and user interface logic.


1 Answers

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).

like image 139
Jacob Oscarson Avatar answered Sep 21 '22 15:09

Jacob Oscarson