首页 > 解决方案 > How to deal with ContraintViolationException and other Exceptions

问题描述

I have a camel route like this:

this.from(uri).process(e -> {

    String json = e.getIn().getBody(String.class);

    JsonObject message = gson.fromJson(json, JsonObject.class);
    Status status = gson.fromJson(message.get("data"), Status.class);

    e.getIn().setHeader("JSON_OBJECT", message);
    e.getIn().setBody(status);
}).to(jpaStatusUri).process(e -> {
    JsonObject message = (JsonObject) e.getIn().getHeader("JSON_OBJECT");
    StatusDetails details = gson.fromJson(message.get("data"), StatusDetails.class);
    // If the first route was successfull i can get the id of the inserted entity here (this works)
    details.setStatusId(e.getIn().getBody(Status.class).getId());
    e.getIn().setBody(details);
}).to(jpaDetailsUri);

I send the entity Status to a jpa endpoint jpaStatusUri. The entity is inserted, and in the following process() method i create a corresponding StatusDetails entity, set it's statusId to the id of the previously saved Status and send it to the jpaDetailsUri endpoint.

This works as expected in case the Status entity has been saved successfully. In case of a ConstraintViolationException i.e. a unique key for the Status entity already exists this will throw the exception, i will not have a correct statusId and i will not be able to update the corresponding StatusDetails entity anymore.

Of course i could all handle this in the process() method, but what would be the "camel-way" to handle this ?

标签: spring-bootjpaapache-camel

解决方案


处理此类事情的骆驼方式是使用onException

 onException(ConstraintViolationException.class)
     .process(e -> {e.getIn().setBody(new ErrorObjectJson());})
     .handled(true)

查看文档

Camel 还提供了try-catch处理异常的方法。


推荐阅读