我正在开发一个 WSO2 ESB 项目,我对如何正确处理故障情况有所怀疑。
例如,我有这个API:
<?xml version="1.0" encoding="UTF-8"?>
<api context="/weather/crop_calendar" name="crop_calendar" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="GET" uri-template="/country/{countryId}/crops?lang={lang_id}">
<inSequence>
<log level="full"/>
<property expression="get-property('uri.var.countryId')" name="countryId" scope="default" type="STRING"/>
<property expression="$url:lang" name="langId" scope="default" type="STRING"/>
<log level="custom">
<property expression="$ctx:countryId" name="countryId"/>
<property expression="$ctx:langId" name="langId"/>
</log>
<property name="messageType" scope="axis2" type="STRING" value="application/xml"/>
<payloadFactory media-type="xml">
<format>
<ds:GetCropCalendarCommoditiesList xmlns:ds="http://ws.wso2.org/dataservice">
<country_id>$1</country_id>
<ds:language_id>$2</ds:language_id>
</ds:GetCropCalendarCommoditiesList>
</format>
<args>
<arg evaluator="xml" expression="$ctx:countryId"/>
<arg evaluator="xml" expression="$ctx:langId"/>
</args>
</payloadFactory>
<header name="Action" scope="default" value="urn:SelectCropCalendarCommoditiesList"/>
<call>
<endpoint key="cropCalendarEndpoint"/>
</call>
<property name="messageType" scope="axis2" type="STRING" value="application/json"/>
<property expression="json-eval($.)" name="JSONPayload" scope="default" type="STRING"/>
<script language="js"><![CDATA[var log = mc.getServiceLog();
function scan(obj) {
var k;
if (obj instanceof Object) {
for (k in obj){
if (obj.hasOwnProperty(k)){
obj[k] = checkForNull(obj[k]);
//recursive call to scan property
scan(obj[k]);
}
}
} else {
//not an Object so obj[k] here is a value
}
}
function checkForNull(value) {
if (value instanceof Object && "@nil" in value) {
return null;
}
return value;
}
log.info("----------------------------- CROP CALENDARD COMMODITIS LISTING SCRIPT START ------------------------------------------------");
var lang_id = mc.getProperty('langId');
// stange workaround for getting JSON Payload. getPayloadJSON returned null.
var pl_string = mc.getProperty("JSONPayload");
log.info("PAYLOAD STRING: " + pl_string);
var payload = JSON.parse(pl_string);
// Create new response:
var response = payload;
log.info("RESPONSE: " + JSON.stringify(response));
scan(response);
// Fix the single element problem:
if (!(response.CropCalendarCommodities.CommoditiesList instanceof Array)) {
log.info("It is not an array, convert it into an array");
singleCommodity = response.CropCalendarCommodities.CommoditiesList;
response.CropCalendarCommodities.CommoditiesList = [];
response.CropCalendarCommodities.CommoditiesList.push(singleCommodity);
}
// Convert array of crops into required HATEOS format
var cropsList = new Array();
for (i = 0; i < response.CropCalendarCommodities.CommoditiesList.length; i++) {
log.info("Crop: " + i + " CROP NAME: " + response.CropCalendarCommodities.CommoditiesList[i].commodity_name);
commodityCropCalendarDetailsLinks = [];
commodityCropCalendarDetailsRefObj = {};
commodityCropCalendarDetailsRefObj.rel = "commodity_enutrifood_details";
commodityCropCalendarDetailsRefObj.href = "http://5.249.148.180:8280/weather/crop_calendar/commodity/" + checkForNull(response.CropCalendarCommodities.CommoditiesList[i].commodity_id) + "?lang=" + lang_id;
commodityCropCalendarDetailsRefObj.type = "GET";
commodityCropCalendarDetailsLinks.push(commodityCropCalendarDetailsRefObj);
response.CropCalendarCommodities.CommoditiesList[i].links = commodityCropCalendarDetailsLinks;
}
log.info("----------------------------- CROP CALENDARD COMMODITIS LISTING SCRIPT END ------------------------------------------------");
// put payload back
mc.setPayloadJSON(response);]]></script>
<property name="RESPONSE" scope="default" type="STRING" value="true"/>
<header action="remove" name="To" scope="default"/>
<send/>
</inSequence>
<outSequence/>
<faultSequence>
// HERE HANDLE THE ERROR CASES
</faultSequence>
</resource>
</api>
此API在URL中包含2个输入参数:
并使用它们执行DSS查询,然后在 JSON 文档中转换查询输出,然后脚本中介处理此JSON文档。
在此调解员链中可能会发生错误。
例如,传递与国家/地区相关的 countryId ,因此数据库中没有数据,DSS查询会返回类似这样的内容(在JSON转换后):
{"CropCalendarCommodities":null}
问题是,当脚本介体处理此文档时,WSO2会出错,因为无法访问此元素到以前的JSON中:
CropCalendarCommodities.CommoditiesList
我得到的错误是这样的:
TID: [-1234] [] [2018-06-13 10:26:58,527] ERROR {org.apache.synapse.mediators.bsf.ScriptMediator} - The script engine returned an error executing the inlined js script function mediate {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "CommoditiesList" from null (<Unknown Source>#45) in <Unknown Source> at line number 45
at com.sun.phobos.script.javascript.RhinoCompiledScript.eval(RhinoCompiledScript.java:68)
at javax.script.CompiledScript.eval(CompiledScript.java:92)
at org.apache.synapse.mediators.bsf.ScriptMediator.mediateForInlineScript(ScriptMediator.java:345)
at org.apache.synapse.mediators.bsf.ScriptMediator.invokeScript(ScriptMediator.java:265)
at org.apache.synapse.mediators.bsf.ScriptMediator.mediate(ScriptMediator.java:233)
at org.apache.synapse.mediators.AbstractListMediator.mediate(AbstractListMediator.java:97)
at org.apache.synapse.mediators.base.SequenceMediator.mediate(SequenceMediator.java:260)
at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.mediateFromContinuationStateStack(Axis2SynapseEnvironment.java:775)
at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:282)
at org.apache.synapse.core.axis2.SynapseCallbackReceiver.handleMessage(SynapseCallbackReceiver.java:554)
at org.apache.synapse.core.axis2.SynapseCallbackReceiver.receive(SynapseCallbackReceiver.java:188)
at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
at org.apache.synapse.transport.passthru.ClientWorker.run(ClientWorker.java:262)
at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.mozilla.javascript.EcmaError: TypeError: Cannot read property "CommoditiesList" from null (<Unknown Source>#45)
我怀疑是:
处理这种情况的最佳方法是什么?
我知道我可以处理脚本调解器内部的情况(这很简单:我检查 CropCalendarCommodities.CommoditiesList 是否 null 。如果是null我创建了一个将返回给用户的propper JSON响应(包含 404 状态消息的内容)。
但我怀疑的是:我能否在 ... 序列中集中管理所有可能的错误案例。
如果在这种情况下为是,我需要一种方法来检索我的 中出现的错误类型。
在这种情况下,如果错误发生在脚本调解器中,我可以构建一个 404 状态消息,该消息将返回给用户。但是如果发生了另一个错误的错误(例如DSS无法访问数据库),我将构建一个不同的错误消息,该消息将返回给用户。
我要做的是集中错误管理并以更典型的异常概念的方式处理错误情况。
我能以某种方式这样做吗?
答案 0 :(得分:1)
是故障序列是处理错误的地方。你可以用,
您可以使用适当的HTTP_SC创建自定义错误有效内容并响应客户端。
答案 1 :(得分:1)
当发生错误时将调用故障序列,最好在那里放置一些东西,否则客户端将继续等待响应。有关详细信息,请参阅the error handling docs。
要记住的一件事是,在DSS中,如果数据库返回错误,则不会导致调用faultsequence。您需要设置FORCE_ERROR_ON_SOAP_FAULT属性。
如果你有一组你想要以不同方式处理错误的调解员,可以考虑将它们移到开启Sequence(我们称之为CodeSeq)。然后创建另一个包含错误处理的序列(让我们称之为ErrorSeq)。然后在CodeSeq中,您可以指定错误属性onError="ErrorSeq"
。