Mapping of custom exception in JAX

I am developing a Client-Server app with JAX-RS / Apache CXF , JSON

I would like Apache CXF to handle my exception transparently on both ends : Which means transforming the exception into a bean, serializing it with my Jackson Serializer (JSON) and then doing the over way around on client side.

I have seen several confusing posts/answers on this subject and came up with using the @WebFault annotation :

@WebFault(name=CODE, faultBean="foo.bar.FaultBean")
public class DuplicateRuleNameFault extends Exception {
   static final public String CODE = "DUPLICATE_RULE_NAME";
   private FaultBean faultBean;

   public DuplicateRuleNameFault(String msg) {
     super(msg);
     this.faultBean = new FaultBean(msg);
   }
   public DuplicateRuleNameFault() {
   }
   public FaultBean getFaultBean() {
     return faultBean;
   }
   public void setFaultBean(FaultBean faultBean) {
     this.faultBean = faultBean;
   }
}

With no success ... Currently, CXF seems to happily ignore the annotation on the Exception and handle it as an unknown exception : 500 status error and no response body generated on the server side.

Is there something specific I have to configure in the "" server element of my Spring context ? I already have Spring scanning my Exception/FaultBean classes (is it even needed BTW ?).

I would appreciate if you could point me at some working example. Thanks.


@WebFault's are not part of the JAX-RS specification. You will want to read up on section 3.3.4 of the specification, which describes the different ways you can accomplish what you are trying to do.

Option 1

Design your resource classes to throw WebApplicationException's. Set the response property of these exceptions to be a valid JAX-RS response containing the fault beans you want to send to the client.

Option 2

Define exception mapping providers. You can create a hierarchy of these to handle all the common exceptions your application will throw. Or you can create a top level exception with an embedded bean and an exception handler for it. And then derive several specific exceptions from the top level one.

public abstract class MyApplicationException<T> extends Exception {
    private T faultBean;

    // Constructors, setters/getters
}

@Provider
public class MyApplicationExceptionHandler implements ExceptionMapper<MyApplicationException<?>> {
    // Implementation
}

One way of doing this is by using the javax.ws.rs.core.Response object like so :

@GET

@Path("/")

public Response getBlah()

{

try {
    return Response.status(Response.Status.OK)
            .entity(<Object you want to return>).build();
}
catch (final DuplicateRuleNameFault e) {
    return Response.status(Response.Status.BAD_REQUEST)
            .entity(e.getFaultBean().getMsg()).build();
}

}

链接地址: http://www.djcxy.com/p/45618.html

上一篇: 处理JAX中的自定义错误响应

下一篇: 在JAX中映射自定义异常