简体   繁体   中英

Modifying the Apache cxf JAX RS response using outbound interceptor

I have developed Rest Application (JAX RS) using Apache CXF.

CXF configuration:

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

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. This makes client ambiguous and unaware of exact cause of the issue. To make it helpful for client you can implement CXF exception handlers.

You can try using ExceptionMapper for this purpose. You need to create ExceptionHandler for your custom BusinessException (or any other) and

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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