使用出站拦截器修改 Apache cxf JAX RS 响应

Modifying the Apache cxf JAX RS response using outbound interceptor

我使用 Apache CXF 开发了 Rest 应用程序 (JAX RS)。

CXF 配置:

<jaxrs:server id="InternalRS" address="/V1">
    <jaxrs:serviceBeans>
        <ref bean="InternalService" />
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <ref bean="jsonProvider" />
    </jaxrs:providers>
    <jaxrs:inInterceptors>
        <bean id="CustomInterceptor"
            class="com.test.web.interceptor.CustomInterceptor">
        </bean>
    </jaxrs:inInterceptors>
</jaxrs:server>

入站拦截器:

public class CustomInterceptor extends AbstractPhaseInterceptor<Message> {

public CustomInterceptor() {
    super(Phase.READ);
}

@Override
public void handleMessage(Message message) throws Fault {
    HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);      
    Transaction transaction = new Transaction();      
    String id = request.getHeader("id");     
    transaction.setId(id);       
    message.getExchange().put("transaction", transaction);
}

}

有什么方法可以通过使用出站拦截器修改 JSON 响应,将我的应用程序抛出的业务异常转换为其等效的 HTTP 状态代码。

与您的情况一样,业务服务会因某些情况抛出自定义异常。如果没有任何特殊处理,CXF 将 return 出现 500 错误并丢失自定义异常。这使客户模棱两可并且不知道问题的确切原因。为了使其对客户有所帮助,您可以实施 CXF 异常处理程序。

您可以尝试使用 ExceptionMapper 来达到这个目的。您需要为自定义 BusinessException(或任何其他)和

创建 ExceptionHandler
package com.gs.package.service;

public class ExceptionHandler implements ExceptionMapper<BusinessException> {
    public Response toResponse(BusinessException exception) {

        //you can modify the response here
        Response.Status status;

        status = Response.Status.INTERNAL_SERVER_ERROR;

        return Response.status(status).header("exception", exception.getMessage()).build();
    }
}

并在您的提供商列表中启用

<jaxrs:server id="sampleREST" address="/rest">
    <jaxrs:serviceBeans>
        <ref bean="yourSerivceBean">
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <bean class="com.gs.package.service.ExceptionHandler"/>
    </jaxrs:providers>
</jaxrs:server>