3

I am experimenting with using Mule 3.4.0CE to provide a RESTful API and evaluating both the Jersey and Rest-router modules to handle this. That is mostly going well but I am not finding very much in terms of concrete/complete examples of implementing RESTful APIs in Mule.

At present I have simple GET and PUT endpoints for an entity working using the rest-router. The PUT flow is successfully passing stuff through to JDBC but I am fizzy about how to handle the case where the entity already exists.

I am ok with relying on SqlException to catch the pk constraint violation and have an exception strategy handling that:

<catch-exception-strategy when="#[exception.causedBy(java.sql.SQLException) and exception.getCauseException().getMessage().contains('Duplicate entry')]" doc:name="Duplicate_entry1">
          <set-payload value="The request cannot be processed, the error is #[exception.getSummaryMessage()]" doc:name="Set Payload"/> <!-- [1] -->
          <set-property propertyName="http.status" value="400" doc:name="Property"/> <!-- [2] -->
</catch-exception-strategy>

but am confused about 2 things:

1) Catching a more specific Exception? I am able to get the exception strategy to match on java.sql.SQLException but would rather match on the root cause of com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException. Using that class and the various forms of casusedBy(), causedExactlyBy() and casueMatches() dont seem to find anything other than the outer SQLException.

and

2) How to return a simple json encoded payload in response to this error? What I would like to do inside the catch-exception-strategy is to create a map of KV pairs something like status="error" and error_message="entity XX already exists" and have that json encoded as the mule payload/ response.

I am embarrassed that I cant seem to get my head around a way to do that simply with MEL or the various components in MuleStudio. Looking for pointers or docs on how to do this. I am resisting building a custom component to return the map I want and have that json encoded on the way out of Mule.

4

2 回答 2

1

对于 1) 在您的 when 子句中,您可以使用org.mule.util.ExceptionUtils的containsType()方法(构建在 Apache ExceptionUtils 类之上)。它检查整个堆栈跟踪是否存在特定异常。 如果您不想在 MEL 中提供完全限定的类名(对于 ExceptionUtils),您可以使用全局导入功能,在MEL Cheat Sheet的最后部分中进行了描述。 我已经发表了两篇关于 Mule 上的 RESTful 服务的 博文(此处此处)。也许,您会发现它们很有用。


于 2013-11-06T22:11:01.870 回答