Error Handling with CXF Interceptors - Modifying a Reply Message

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

I did not find any suitable documentation that could tell me how to do this ...

These axometers are designed for REST, but I would also like to handle this in SOAP.

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> 
+7
source share
2 answers

And here is another piece of your puzzle . You are already using JAX-RS , so why not use JAX-WS ?

This thread and this cover mapping blog post are exceptions to SOAP errors. Briefly and clearly:

The JAX-WS 2.0 specification requires that an exception annotated with @WebFault must have two constructors and one method [getter to get fault information]:

 WrapperException(String message, FaultBean faultInfo) WrapperException(String message, FaultBean faultInfo, Throwable cause) FaultBean getFaultInfo() 

WrapperException is replaced by the name of the exception, and FaultBean is replaced by the name of the class that implements the bean error. Error bean is a Java bean that contains information about a failure and is used by the web service client to find out the cause of the failure.

And here is your mapping. Just specify the implementations of the above signatures in the context of @WebFault , and your SOAP API should display them correctly. Obviously, the links contain more detailed information.

+5
source

If you are using JAX-RS, why not configure the exception configurator, then use this handler 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 will need to register the provider with jaxrs by adding:

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

in the server configuration in context. At the same time, you have full access to the exception and you can get everything you want from it.

+13
source

All Articles