简体   繁体   中英

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();

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()
        ;

You can use conditional trapping u can predicate for every case

 onException(HttpOperationFailedException.class)
            .onWhen(exchangeProperty("CamelExceptionCaught").isEqualTo("404")).to("direct:go404")
            .onWhen(exchangeProperty("CamelExceptionCaught").isEqualTo("500")).to("direct:go500");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM