出于某些原因,我有一个创建实体记录的javascript,并且会在创建后触发插件。如果pugin抛出异常,它不会显示给用户,因为涉及到javascript。我想知道是否有办法将插件中的异常传递给javascrit,以便它可以将其显示给用户。
感谢。
答案 0 :(得分:0)
您是否收到任何http状态代码错误,如40 *,500,50 *,如果您使用Odata,您有回调来获取错误。 Javascript异常可能不会被抛出。
示例:
.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8″,
datatype: “json”,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert(“Error on the creation of record; Error – “+errorThrown);
}
});
}
答案 1 :(得分:0)
检查XMLHttpRequest readyState和status应该可以解决这个问题:
function createRecord(eObject, eName) {
var jsonEntity = window.JSON.stringify(eObject);
var u = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var rec = new XMLHttpRequest();
var p = u + ODATA_ENDPOINT;
rec.open('POST', p + "/" + eName, false);
rec.setRequestHeader("Accept", "application/json");
rec.setRequestHeader("Content-Type", "application/json; charset=utf-8");
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status == 200) {
var r = JSON.parse(rec.responseText).d;
return r;
}
else {
var error;
try {
// To get the exception from the responseXML
// I get an error when trying to use JSON.parse(rec.response)
// Unexpected token <
// I would much rather use JSON.parse
// than fiddling with the XML
// Please let me know if you find how to
// get the error message with JSON.parse
var xmlDoc = rec.responseXML;
var error = xmlDoc.childNodes[0]
.childNodes[0]
.childNodes[0]
.childNodes[1]
.childNodes[0].nodeValue + "."; // The error message
}
catch (e) {
// unable to get error message from response
error = "General Error";
}
return error;
}
}
// there is a problem
// maybe return general error message
return "General Error";
}
答案 2 :(得分:0)
谢谢你们所有人。我确实通过将部分代码修改为以下内容来解决问题:
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status >= 200) {
var newRecord = JSON.parse(rec.responseText).d;
return newRecord;
}
else {
var error;
var er;
try {
error = rec.responseText.toString();
error = error.substring(error.lastIndexOf("value\": ")+9,error.lastIndexOf("\""));
alert(error);
}
catch(e) {
error = rec.responseText.toString();
error = encodeURIComponent(error);
er = error.substring(error.lastIndexOf("value%22%3A%20%22")+17,
error.lastIndexOf("%22%0D%0A%7D%0D%0A%7D%0D%0A%7D"));
er = decodeURIComponent(er);
return er;
}
}