我一直在研究和测试您的问题。问题是从CXF拦截器抛出的异常逃避了JAX-
RS流(请参阅
CXF团队的答案)
甲
Fault从拦截器产生可以被获取,实现
handleFault在拦截器本身
public void handleFault(Message message) { Exception e = message.getContent(Exception.class); }
或实施
FaultListener并在CXF总线上注册
WebClient.getConfig(client).getBus().getProperties().put("org.apache.cxf.logging.FaultListener",new MyFaultListener());public class MyFaultListener implements FaultListener{ public boolean faultOccurred(final Exception exception,final String description,final Message message) { //return false to avoid warning of default CXF logging interceptor return false; }}
但是您不能从拦截器返回自定义响应,也不能对客户端响应故障。
我发现实现所需行为的解决方法是将Response替换为可以由您的常规方法调用处理的自定义对象
进入
Interceptor.handleMessage检查你所需要的条件,并创建一个
Response自定义状态和实体。之后,停止链条
public class MyInterceptor extends AbstractPhaseInterceptor<Message> { public MyInterceptor() { super(Phase.POST_STREAM); } @Override public void handleMessage(Message message) throws Fault { if (message != null) { //check the condition to raise the error //build the custom Response replacing service call Response response = Response .status(Response.Status.BAD_REQUEST) .entity("custom error") .build(); message.getExchange().put(Response.class, response); //abort interceptor chain in you want to stop processing or throw a Fault (catched by handleFault) //message.getInterceptorChain().abort(); //throw new Fault (new MyException()); } public void handleFault(Message messageParam) { }}
创建JAXRS客户端时,将ResponseExceptionMapper添加为提供者
providers.add(new ResponseExceptionMapper<WebApplicationException>() { @Override public WebApplicationException fromResponse(Response r) { return new WebApplicationException(r); }});YourService proxy = JAXRSClientFactory.create(url, clazz,providers);Client client = WebClient.client(proxy);WebClient.getConfig(client).getInInterceptors().add(new MyInterceptor());
此后,对的调用
proxy.yourService()将引发
WebApplicationExceptionif如果完成拦截器检查。您可以按期望的方式抓住它或将其扔掉
try{ proxy.yourService();}catch (WebApplicationException e){}
希望这可以帮助
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)