我正在使用 apache camel 从我的应用程序中公开 rest 端点。 当 rest 端点成功执行时,它会返回预期的 JSON 响应,如下所示。
{
"key1": "value1",
"key2": 123
}
当出现异常时,onException camel 子句被执行,在这种情况下它不返回 json 响应,而是返回如下所示的 java 对象表示形式
com.mypackage.Response@27f674d
示例路线定义如下。
rest("")
.consumes("application/json")
.produces("application/json")
.post("/endpoint")
.bindingMode(RestBindingMode.json)
.type(Request.class)
.outType(Response.class)
.to("direct:endpoint")
路由端点定义
onException(Exception.class)
.process(new ExceptionProcessor())
.convertBodyTo(Response.class)
.handled(true);
from("direct:endpoint")
.streamCaching()
.process(...)
.process(...)
.end()
ExceptionProcessor 示例实现。
public class ExceptionProcessor implements Processor{
public void process(Exchange exchange) throws Exception{
Response res = new Response();
res.setKey1("value1");
res.setKey2(123);
exchange.getMessage().setBody(res);
}
}
为什么 onException 返回响应作为 java 对象字符串表示? 如何在异常情况下返回 JSON 响应?