skip to Main Content

I need to return the message from a thrown exception, or put it in the outmessage. But it does not print the correct message on the frontend.

The camel docs suggest using .transform(simple?...) .handled(true) but most of it is deprecated.

What’s the correct way of doing this?

Response:

<418 I'm a teapot,simple{${exception.message}},{}>

Route

from("direct:csv")
  .doTry()
    .process(doSomeThingWithTheFileProcessor)
  .doCatch(Exception.class)
    .process(e -> {
        e.getOut().setBody(new ResponseEntity<String>(exceptionMessage().toString(), HttpStatus.I_AM_A_TEAPOT));
    }).stop()
  .end()
  .process(finalizeTheRouteProcessor);

doSomethingWithFileProcessor

public void process(Exchange exchange) throws Exception {
        String filename = exchange.getIn().getHeader("CamelFileName", String.class);

        MyFile mf = repo.getFile(filename); //throws exception

        exchange.getOut().setBody(exchange.getIn().getBody());
        exchange.getOut().setHeader("CamelFileName", exchange.getIn().getHeader("CamelFileName"));
    }

2

Answers


  1. There is a lot of ways how to do it. All of it is correct, choose your favourite depending on complexity of error handling. I have published examples in this gist. None of it is deprecated in Camel version 2.22.0.

    With Processor

    from("direct:withProcessor")
            .doTry()
                .process(new ThrowExceptionProcessor())
            .doCatch(Exception.class)
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        final Throwable ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
                        exchange.getIn().setBody(ex.getMessage());
                    }
                })
            .end();
    

    With Simple language

    from("direct:withSimple")
            .doTry()
                .process(new ThrowExceptionProcessor())
            .doCatch(Exception.class)
                .transform().simple("${exception.message}")
            .end();
    

    With setBody

    from("direct:withValueBuilder")
            .doTry()
                .process(new ThrowExceptionProcessor())
            .doCatch(Exception.class)
                .setBody(exceptionMessage())
            .end();
    
    Login or Signup to reply.
  2. In the doCatch() Camel moves the exception into a property on the exchange with the key Exchange.EXCEPTION_CAUGHT (http://camel.apache.org/why-is-the-exception-null-when-i-use-onexception.html).

    So you can use

    e.getOut().setBody(new ResponseEntity<String>(e.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class).getMessage(), HttpStatus.OK));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search