added errorProcessor option to RESTAdapter #1291

Closed
wants to merge 1 commit into
from

Projects

None yet

3 participants

@marcoow
marcoow commented Sep 13, 2013

This adds an errorProcessor option to the RESTAdapter that allows for easy handling of server-sent validation errors. Instead of having to override the full RESTAdapter.ajax method one could not simply specify the errorProcessor function like e.g. headers:

DS.RESTAdapter.reopen({
  errorProcessor: function(jqXHR, textStatus, errorThrown) {
    if (jqXHR.status === 422) {
      return JSON.parse(jqXHR.responseText).errors;
    }
  }
});

When that handler returns sth., the adapter wraps that in a DS.InvalidError so that the errors get assigned to the model's errors property.

Unfortunately I don't see a good way to test this as the ajax method is stubbed out in the RESTAdapter tests and I didn't want to add a dependency to stub on a lower level. Would be glad to add tests of course given some advice on how to do it.

@gerry3
Contributor
gerry3 commented Sep 25, 2013

@marcoow the RESTAdapter has an ajaxError method now you can use for this:

  /**
    Takes an ajax response, and returns a relavant error.

    By default, it has the following behavior:

    * It simply returns the ajax response.

    @method ajaxError
    @param  jqXHR
  */
  ajaxError: function(jqXHR) {
    if (jqXHR) {
      jqXHR.then = null;
    }

    return jqXHR;
  }

For example, the ActiveModelAdapter does this:

/**
  The ActiveModelAdapter overrides the `ajaxError` method
  to return a DS.InvalidError for all 422 Unprocessable Entity
  responses.

  @method ajaxError
  @param jqXHR
  @returns error
*/
ajaxError: function(jqXHR) {
  var error = this._super(jqXHR);

  if (jqXHR && jqXHR.status === 422) {
    var json = JSON.parse(jqXHR.responseText);
    return new DS.InvalidError(json["errors"]);
  } else {
    return error;
  }

You will probably want to run return your processed errors hash as a new DS.InvalidError(...) so that becameInvalid is called on your record (via adapterDidInvalidate via recordWasInvalid).

@bradleypriest
Member

@marcoow sounds like the ajaxError hook should handle your situation, if not feel free to reopen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment