How to handle server response errors with ember data

ember-data, ember.js

Solution

@colymba got it almost right, but I'll try to make a more elaborated answer so it helps you get up and running easier.

As already stated in the new router facelift when an attempt is made to transition into a route, any of the hooks `beforeModel`, `model` and `afterModel` may throw an error, or return a promise that rejects, in this case an `error` event will be fired on the partially entered route, allowing you to handle errors on a per route basis.

App.SomeRoute = Ember.Route.extend({
  model: function() {
    //assuming the model hook rejects due to an error from your backend
  },
  events: {
   // then this hook will be fired with the error and most importantly a Transition
   // object which you can use to retry the transition after you handled the error
   error: function(error, transition) {
     // handle the error
     console.log(error.message);
     // retry the transition
     transition.retry();
  }
});

In the case you want to have errors be handled application wide you can define your own global default `error` handler by overriding the `error` handler on the `ApplicationRoute`, this could look something like this:

App.ApplicationRoute = Ember.Route.extend({
  events: {
    error: function(error, transition) {
      // handle the error
      console.log(error.message);
    }
  }
});

Take into account that by default, an event will stop bubbling once a handler defined on the `events` hash handles it. But to continue bubbling the event all the way up to the `ApplicationRoute` you should return `true` from that handler, so it can notify more `error` handler from which you can then retry to make the transition to the route with `transition.retry()`.

Update for ember 1.0 and upwards

Since the new ember release 1.0, the `events` hash was renamed to `actions`. A route's error handler should be in the `actions` hash now:

App.ApplicationRoute = Ember.Route.extend({
  actions: {
    error: function(error, transition) {
      // handle the error
      console.log(error.message);
    }
  }
});

Hope this helps you.

Problem

What is the ember-data's current default expected response from the server if it got something other than 200, so it doesn't throw an uncaught exception but instead parses the errors for later use? e.g. {"errors":{jsonerror}} ??? How should I handle server error responses (json format) in Ember? Thanks!

Original source

Related problems