如何正确管理 WSO2 ESB 错误情况?我可以将所有错误情况集中在 FaultSequence 中吗?
我正在开展 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 个输入参数:
- countryId
- lang_id
并使用两者执行 DSS 查询,然后将查询输出转换为 JSON 文档,然后 Script mediator 处理此 JSON 文档。
在此中介链中可能会发生错误。
例如,传递与国家/地区相关的 countryId ,因此数据库中没有数据,DSS 查询返回类似以下内容(经过 JSON 转换):
{"CropCalendarCommodities":null}
问题是当 Script 中介处理此文档时,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 。如果为空,我会创建一个适当的 JSON 响应,该响应将返回给用户(包含 404 状态消息)。
但我的疑问是:我能否集中管理 ... 序列中所有可能的错误情况。
如果是,在这种情况下,我需要一种方法来检索发生在我的 中的错误类型。
在这种情况下,如果错误发生在 脚本中介 中,我可以构建一个 404 状态消息,该消息将返回给用户。但如果发生了另一种类型的错误(例如 DSS 无法访问 DB),我将构建一个不同的错误消息,该消息将返回给用户。
我想做的是集中错误管理,并以更类似于传统异常概念的方式处理错误情况。
我能以某种方式做到这一点吗?
是的,故障序列是处理错误的地方。您可以使用,
- get-property('ERROR_CODE')
- get-property('ERROR_MESSAGE')
您可以使用适当的 HTTP_SC 创建自定义错误负载并响应客户端。
当发生错误时,将调用故障序列,最好在那里放置一些内容,否则客户端将继续等待响应。有关更多信息,请参阅 错误处理文档 。
需要记住的一件事是,在 DSS 中,如果数据库返回错误,这不会导致调用故障序列。您需要设置 FORCE_ERROR_ON_SOAP_FAULT 属性。
如果您有一组中介器,想要以不同的方式处理错误,请考虑将它们移动到其 on
Sequence
(我们称之为 CodeSeq)。然后,您创建另一个包含错误处理的序列(我们称之为 ErrorSeq)。然后在 CodeSeq 中,您可以指定 on error 属性
onError="ErrorSeq"
。