Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling with CXF interceptors - changing the response message

I'm trying to handle errors coming from my backend. The handleMessage() is called if an error occurs but the content is an instance of XmlMessage. I would like to change it to my own response - just set the response code and add some message.

I haven't found any proper documentation which could tell me how to do this...

These axamples are for REST but I'd like to manage this thing in SOAP too.

interceptor

public class ErrorHandlerInterceptor extends AbstractPhaseInterceptor<Message> {

    public ErrorHandlerInterceptor() {
        super(Phase.POST_LOGICAL);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        Response response = Response
            .status(Response.Status.BAD_REQUEST)
            .entity("HOW TO GET A MESSAGE FROM AN EXCEPTION IN HERE???")
            .build();
        message.getExchange().put(Response.class, response);
    }

}

context.xml

<bean id="errorHandlerInterceptor"
    class="cz.cvut.fit.wst.server.interceptor.ErrorHandlerInterceptor" />

<jaxrs:server address="/rest/">
    <jaxrs:serviceBeans>
        <ref bean="restService" />
    </jaxrs:serviceBeans>
    <jaxrs:outFaultInterceptors>
        <ref bean="errorHandlerInterceptor" />
    </jaxrs:outFaultInterceptors>
</jaxrs:server>
like image 373
user219882 Avatar asked Apr 08 '12 16:04

user219882


1 Answers

If you're using JAX-RS, why not setup an exception mapper, and then use that mapper to handle the response.

A simple example:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class MyExceptionMapper implements
        ExceptionMapper<MyException> {

    @Override
    public Response toResponse(MyException e) {
        return Response.status(Status.NOT_FOUND).build();
    }

}

Then you would need to register the provider in the jaxrs serve by adding:

<jaxrs:providers>
    <bean class="com.blah.blah.blah.blah.MyExceptionMapper"/>  
</jaxrs:providers>

in the server config in the context. With that you have full access to the exception, and can get whatever you want from it.

like image 118
mjwenk Avatar answered Oct 14 '22 16:10

mjwenk