Search code examples
jsonapache-cameloutputprocessor

Apache Camel Custom Exit Error


I have the following Apache camel to make a post to a URL.

        .setHeader(HTTP_PATH,simple("/product-catalog/insert"))
        .setHeader(HTTP_METHOD,constant("POST"))
        .setHeader(CONTENT_TYPE, constant("application/json"))
        .setBody(constant(""))
        .process(new ProductProcessor())
        .marshal().json(JsonLibrary.Jackson)
        .to("{{products.endpoint}}?bridgeEndpoint=true")
        .unmarshal().string()
        .setHeader("CamelJacksonUnmarshalType", constant(ProductInsertResponse.class.getName()))
        .unmarshal(ProductResponse)
        .process(new ProductResponseProcessor())

After this call, on the processor I would like to check if the product code for this new product is correct, as follow:

public class ProductResponseProcessor implements Processor 
{

    @Override
    public void process(Exchange exchange) throws Exception {

        ProductInsertResponse response = (ProductInsertResponse) exchange.getIn().getBody();

        if(response.productCode().equals("0")){
            // The product code is not correct
            // And I would like to return a JSON to the browser with the following format
            // {"response":"Error","errorString":"Error insert product" ,"errorCode":"0"}
        }
    }
}

if the code is not 0 I would like to continue with my other task in the apache camel flow. I don't know how to cut the route on this point and send a JSON object to the browser in case of our product code is equal to 0.

Thank you so much.


Solution

  • You have number of different options.

    simple ones:

    • throw exception from your processor and then catch it in the route in onException or surround your processor with camel doTry

    • set special Exchange property in the processor then analyze it in the route and fork your flow as you need. ...