Skip to content
Advertisement

How to handle 4xx(without retry) and 5xx (with retry) exceptions in camel

I’ve a camel route which makes API request, the external service may though 4xx or 5xx. I have written HttpOperationFailedException handler to handle all HTTP related exception and I’m retrying all the Http exceptions irrespective of whether its client side or server side exceptions. I would like to handle them in a way, I need to avoid the reties for client side exceptions.

Here is my route and exception code, looks like. Can anyone suggest best way to handle these scenarios ?

  onException(HttpOperationFailedException.class)
        .handled(true)
        .redeliveryDelay(100)
        .maximumRedeliveries(2)
        .log("${exception} Http Communication Exception while making API request")
        .end();


from("direct:start")
        .routeId("restApi")
        .process(exchange -> exchange.getIn().setBody(
            new RequestBody(
                "${headers.camelFileName}")))
        .marshal()
        .json(JsonLibrary.Gson)
        .setHeader(Exchange.HTTP_METHOD, constant("POST"))
        .setHeader("Content-Type",constant("application/json"))
        .to(url)
        .end();

Advertisement

Answer

You could try something along the lines of:

        onException(HttpOperationFailedException.class)     
                .choice()
                    .when(simple("${exception.getStatusCode()} == '400'"))
                     //doSomething
                    .endChoice()
                    .when(simple("${exception.getStatusCode()} == '500'"))
                     //doSomething
                    .otherwise()
                    //retries
                    .endChoice()
                .end()
        ;
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement