Apache Camel:如何获取 doCatch() 块内的异常消息?

Edw*_*ard 3 apache dsl apache-camel spring-boot

我需要从抛出的异常中返回消息,或者把它放在 outmessage 中。但它不会在前端打印正确的消息。

骆驼文档建议使用,.transform(simple?...) .handled(true)但其中大部分已弃用。

这样做的正确方法是什么?

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


路线

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);
Run Code Online (Sandbox Code Playgroud)


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"));
    }
Run Code Online (Sandbox Code Playgroud)

Bed*_*dla 9

有很多方法可以做到。所有这些都是正确的,根据错误处理的复杂程度选择您最喜欢的。我已经在这个 gist 中发布了示例。在 Camel 版本中没有一个被弃用2.22.0

带处理器

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();
Run Code Online (Sandbox Code Playgroud)

用简单的语言

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

使用 setBody

from("direct:withValueBuilder")
        .doTry()
            .process(new ThrowExceptionProcessor())
        .doCatch(Exception.class)
            .setBody(exceptionMessage())
        .end();
Run Code Online (Sandbox Code Playgroud)