Saturday, 16 March 2013

Dynamics CRM 2011 - Propagate the plug-in invalid exception message in JavaScript code.

Recently I came across an issue where I would like to propagate the plug-in InvalidPluginExcecutionException message via JavaScript code. Based on the client requirements I need to trigger a plug-in on click of custom ribbon button on the Opportunity entity. Hence on custom button click I have written a web service call that updates one of custom attributes of an Opportunity entity. So, when system will update this field via client side web service call, the registered plug-in will be triggered automatically. Usually your InvalidPluginExcecutionException message inside your plug-in code is displayed to user in a standard CRM message box. In my case I am unable to see the same because the plug-in is being triggered via JavaScript web service call. Below is the code snippet that executes my query.
//Asynchronous AJAX function to update a CRM record using OData

  $.ajax({

    type: "POST",

    contentType: "application/json; charset=utf-8",

    datatype: "json",

    data: jsonEntity,

    url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",

    beforeSend: function (XMLHttpRequest) {

      //Specifying this header ensures that the results will be returned as JSON.             

      XMLHttpRequest.setRequestHeader("Accept", "application/json");

 

      //Specify the HTTP method MERGE to update just the changes you are submitting.             

      XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");

    },

    success: function (data, textStatus, XmlHttpRequest) {

      //The MERGE does not return any data at all, so we'll add the id 

      //onto the data object so it can be leveraged in a Callback. When data 

      //is used in the callback function, the field will be named generically, "id"

      data = new Object();

      data.id = id;

      if (successCallback) {

        successCallback(data, textStatus, XmlHttpRequest);

      }

    },

    error: function (XmlHttpRequest, textStatus, errorThrown) {

      if (errorCallback) {

 

        errorCallback(XmlHttpRequest, textStatus, errorThrown);

      }

      else {

        ErrorHandler(XmlHttpRequest, textStatus, errorThrown);

      }

    }

  }); 


I have validated all the 3 objects i.e. XmlHttpRequest, textStatus and errorThrown inside errorCallback method to seek the plug-in error message with no success. However I can see the same error message via fiddler!!
Finally, I found a way to parse the response text of xmlHttpRequest and get the exact error message. Below is the code that works for me to alert the plug-in message from client side code.


function ErrorHandler(xmlHttpRequest, textStatus, errorThrown) {

 

  alert(JSON.parse(xmlHttpRequest.responseText).error.message.value);

 

}


I hope this will be helpful.



No comments:

Post a comment