【问题标题】:JAX RS CXF Interceptor for throwing client specific exceptions用于抛出客户端特定异常的 JAX RS CXF 拦截器
【发布时间】:2013-04-04 22:57:40
【问题描述】:

我有一个将一组类公开为 RESTful 服务的服务器。我知道我们可以使用ExceptionMapper 将异常传递给客户端。客户端和服务器之间共享的检查异常很少。然而,在我的一些服务中,我几乎没有在客户端 JVM 中不可用的检查异常。

我了解更改端点以确保正确处理检查的异常可以解决问题。

但是,我想在拦截器层这样做有两个原因:

  • 这将是一个我可以处理所有导致检查异常的调用的地方。
  • 由于当前的发布日期,这将是一项重大的重构工作。

查看CXF documentation,我知道我必须扩展AbstractPhaseInterceptor并覆盖handleMessage()

public class MyOutExceptionInterceptor extends AbstractPhaseInterceptor<Message> {

    public AttachmentInInterceptor() {
        //Which phase to call here ??
        super(Phase.POST_INVOKE);
    }

    public void handleMessage(Message message) {

        //Check from message that it contains an exception of MyCheckedException.class
        //Create an exception that client can understand

    }
}

我该怎么做?

提前致谢。

【问题讨论】:

    标签: java exception cxf jax-rs interceptor


    【解决方案1】:

    我知道我迟到了,但我也遇到了这个问题并想出了这个解决方案。因此以供将来参考:

    在内部覆盖handleFault:

    Exception fault = message.getContent(Exception.class);
    Exception exception = fault.getCause();
    YourOwnFault newFault = new YourOwnFault("bla bla bla");
    message.setContent(Exception.class, newFault);
    

    换句话说:提取故障,获取异常作为原因,创建新故障并插入int。

    【讨论】:

    • 您没有使用exception 变量。那你为什么会得到它?
    • 可能在YourOwnFault的构造函数中使用它而不是“bla bla bla bla”。
    【解决方案2】:

    尝试类似:

    public void handleMessage(Message message) {
     // Map exception
        Exception exception = message.getContent(Exception.class);
        Exception mappedException = mapper.map(exception);
    
        Fault fault = exception instanceof Fault ? (Fault) exception : null;
        if (fault == null)
        {
            fault = new Fault(exception);
            message.setContent(Exception.class, fault);
         }
        fillInFaultDetails(fault, exception);
    }
    

    这实际上是我们代码中的一个sn-p(为简洁起见,我省略了映射/填充细节;关键是替换消息内容。)。至于阶段 - 我们在 POST_LOGICAL 运行它; POST_INVOKE 也可以。

    顺便说一句 - 不确定您的用例是什么,但我不喜欢使用故障来传达业务异常(在我看来,故障表示一般消息处理错误而不是业务逻辑异常。

    【讨论】:

    • 感谢您的回复。但是我在带有此代码的链式拦截器中的fault = new Fault(exception); 处得到了一个 RuntimeException。
    • 这是什么异常?
    猜你喜欢
    • 2016-01-06
    • 2012-02-23
    • 2016-12-08
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-09
    • 1970-01-01
    相关资源
    最近更新 更多