简体   繁体   English

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

[英]Modifying the Apache cxf JAX RS response using outbound interceptor

I have developed Rest Application (JAX RS) using Apache CXF. 我使用Apache CXF开发了Rest Application(JAX RS)。

CXF configuration: 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>

Inbound Interceptor: 入站拦截器:

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);
}

} }

Is there any way so that I could convert the business exception thrown by my application to its equivalent HTTP Status Codes by modifying the JSON response with an outbound interceptor. 有没有办法让我可以通过使用出站拦截器修改JSON响应,将我的应用程序抛出的业务异常转换为等效的HTTP状态代码。

As in your case, the business service throws an custom exception due to certain conditions. 与您的情况一样,由于某些条件,业务服务会抛出自定义异常。 Without any special handing CXF will return a 500 error and lose the custom exception. 没有任何特殊处理,CXF将返回500错误并丢失自定义异常。 This makes client ambiguous and unaware of exact cause of the issue. 这使得客户端模棱两可,并且不知道问题的确切原因。 To make it helpful for client you can implement CXF exception handlers. 为了使客户端有用,您可以实现CXF异常处理程序。

You can try using ExceptionMapper for this purpose. 您可以尝试使用ExceptionMapper来实现此目的。 You need to create ExceptionHandler for your custom BusinessException (or any other) and 您需要为自定义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();
    }
}

And enable in your providers list 并在您的提供商列表中启用

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM