Esteban A. Maringolo
Esteban A. Maringolo

Reputation: 1218

Access to HTTP response in Ext.data.Model.save() callbacks using REST proxy

I successfully implemented client editors and a server side API.

Now I'm adding more validation at the server side, and besides returning the proper HTTP code (200 for OK, 4xx for other uses, 500 for errors, etc.) I want to return a list of validations that failed after the submission generated by Model.save().

I run it this way:

myModel.save({
  success: function (a, operation, c) {...},
  failure: function (a, operation, c) {...}
});

But if there was a failure, the operation object only have the response status and its statusText, all through

operation.error.status // i.e. 409
operation.error.statusText // "Conflict"

But server side a detail of the failing validations (mostly domain level ones) are being added to the response.

Is there a way I can get what the server sent as the body of the HTTP response to the PUT/POST submission?

Do I have to return it using a particular JSON structure?

EDIT: I'm now returning this as the body of the HTTP Response (with code 4xx):

{
 data: {/* the record serialized */},
 success: false, // or true if everything went ok
 message: "This failed because X and Y."
}

Thanks in advance.

Upvotes: 3

Views: 3274

Answers (3)

David ...
David ...

Reputation: 19

  1. in reader block add: messageProperty: 'message'
  2. from server return: success:false, message: 'error test'
  3. from failure get error:

    failure: function (records, operation) {
        Ext.Msg.alert('error', operation.error);
    }
    

Upvotes: 0

Eric
Eric

Reputation: 51

According to this blog: http://code.tonytuan.org/2013/07/extjs-get-server-response-in-modelsave.html

You can write code like this:

model.save({
    success: function (record, operation) {
    // json response from server         
    console.log(operation.response);                  
    },
    failure: function (record, operation) {
        // undefined
        console.log(operation.response); 
        // json response from server
        console.log(operation.request.scope.reader.jsonData);
    }
});

Upvotes: 3

Esteban A. Maringolo
Esteban A. Maringolo

Reputation: 1218

For some reason Ext is not attaching the response content to the error object, but it triggers an exception event if there is a failure.

So what we did was to handle the "exception" event of the model's proxy, and then we will have access to the XHR response, being able to do whatever we want with it.

myModel.getProxy().on('exception', this.onProxyException, this);

The handler is as follows:

onProxyException : function (proxy, response, operation) {
    var errors;
    errors = Ext.JSON.decode(response.responseText).message;
    /* Whatever is needed with the errors */
}

In this example we asume the errors come in JSON format, they could be a simple text string, which wouldn't require the use of decode().

Upvotes: 4

Related Questions