Looking for paradigm to use for generic error handling in Angular from a JSON response from Rails Looking for paradigm to use for generic error handling in Angular from a JSON response from Rails angularjs angularjs

Looking for paradigm to use for generic error handling in Angular from a JSON response from Rails


I went ahead and implemented what I thought needed to be done. Thanks for digger69 for some help with this.

On the Rails side, I went with using an http status code. As per here I agreed with using a 400 http status code for error validation.

In my controllers I now have something like the following:

def create  my_obj = MyObj.build_with_params(params)  if my_obj.save    respond_with(my_obj) # regular RABL response  else    respond_with_errors(my_obj.errors)  endend

In my application_controller.rb I defined a common method respond_with_errors

# respond back to the client an http 400 status plus the errors arraydef respond_with_errors(errors)  render :json => {:errors => errors}, :status => :bad_requestend

Note that the :bad_request symbol is already defined for Rails as per here

On the client side I needed to intercept http calls (not only for validation but for authentication failures too (and probably more). Here is an example of my code in Angular (thanks to this post for the help with that):

var interceptor = ['$rootScope', '$q', function (scope, $q) {  function success(response) {    return response;  }  function error(response) {    var status = response.status;    if (status == 401) { // unauthorized - redirect to login again      window.location = "/";    } else if (status == 400) { // validation error display errors      alert(JSON.stringify(response.data.errors)); // here really we need to format this but just showing as alert.    } else {      // otherwise reject other status codes      return $q.reject(response);    }  }  return function (promise) {    return promise.then(success, error);  }}];$httpProvider.responseInterceptors.push(interceptor);

I now can be consistent with my rails code and deal with success returns from http calls on the client. I'm sure I have some more to do, but I think this gives a localized solution.


Use an HTTP response interceptor. I am currently using that successfully in an application.

http://docs.angularjs.org/api/ng.$http

From the documentation:

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {  return function(promise) {    return promise.then(function(response) {      // do something on success    }, function(response) {      // do something on error      if (canRecover(response)) {        return responseOrNewPromise      }      return $q.reject(response);    });  }});$httpProvider.responseInterceptors.push('myHttpInterceptor');

In my case I created a feedback service, which displays either success or error messages globally. An other option would be to broadcast the responses on the rootscope.