【发布时间】:2020-04-04 05:58:02
【问题描述】:
我确实对 Mule 3.9 中的一个案例有疑问。
我的 API 是用 .this .raml 文件生成的。
端点之一就是带有“/”路由的 GET(用于测试目的)。
在这个流程(管理 GET /)中,我想调用另一个流程来检查某事(在我的情况下是 JWT 验证)。什么时候有效我想传递,并返回原始有效负载。当无效时,我在 Groovy 中调用了一个异常,这确实发生了,但毕竟它涉及到同源有效负载,它不应该是可见的。
让我们编写一些代码:
源流:
<flow-ref name="validate_jwt_token" doc:name="Validate JWT"/>
<set-payload value=" { "message" : "API is working!"}" doc:name="Set Payload" mimeType="application/json" />
</flow>
和流程参考:
<flow name="validate_jwt_token">
<logger message="Request found with Authorization: #[message.inboundProperties['authorization']]" level="INFO" doc:name="Loger Authorization"/>
<component doc:name="Validate JWT Token">
<spring-object bean="ValidateJWTEvent"/>
</component>
<choice doc:name="Choice">
<when expression="(payload == true)">
<logger message="JWT valid. Access granted." level="INFO" doc:name="Logger"/>
</when>
<otherwise>
<scripting:component doc:name="Throw Exception">
<scripting:script engine="Groovy"><![CDATA[throw new Exception('Invalid JWT Token.')]]></scripting:script>
</scripting:component>
</otherwise>
</choice>
<catch-exception-strategy doc:name="Catch Exception Strategy">
<set-property propertyName="http.status" value="401" doc:name="Set 401 status"/>
<flow-ref name="commons.exceptionStrategy.logError" doc:name="Log errors"/>
</catch-exception-strategy>
</flow>
即使这个令牌实际上是无效的,我也会得到相同的有效负载,其中包含文本“API 正在工作”。我想要做的是捕获异常并返回 HTTP ERROR。仅此而已。
我也附上了我的异常策略。请记住,它基于 APIKIT,生成了我的 Mule selft .raml 文件。
<sub-flow name="commons.exceptionStrategy.logError">
<logger message="Error: #[exception.?cause.message or exception]" level="ERROR" doc:name="Logger" />
<set-property propertyName="Content-Type" value="application/json" doc:name="Set Content Type"/>
<flow-ref name="log_params" doc:name="log_params"/>
<logger message="#[org.apache.commons.lang3.StringEscapeUtils.escapeJson(exception.?getCauseException().?getMessage())]" level="ERROR" doc:name="Display error"/>
<set-payload value="{ "responseHeader": { "requestId": "#[flowVars.storedRequestId]", "sendDate": "#[function:now]"}, "code": "#[flowVars.'statusCode']", "message": "#[flowVars.errorMessage or org.apache.commons.lang3.StringEscapeUtils.escapeJson(exception.?getCauseException().?getMessage())]" }" doc:name="Set Error Message"/>
</sub-flow>
<sub-flow name="log_params">
<logger message="API| endpoint executed with payload: #[message.payload]" level="INFO" doc:name="log payload"/>
<logger message="API| endpoint executed with flowVars: #[flowVars]" level="INFO" doc:name="log params"/>
</sub-flow>
整个 API 由 APIKIT my Mule with Global Catch Exception Strategy 使用。
请帮帮我。
【问题讨论】:
-
请展示异常策略以了解如何处理错误。
-
完成。我已经编辑了上面的帖子。