在CXF中默认的异常处理是无法满足我要的方式的,我需要把异常转换为JSON格式,返回给客户的。这样就只能自定义异常处理了。
JSR已经考虑到了这种情况,少量的编码就可以实现需求。
1.编写自己的ExceptionMapper
JSR已经考虑到了这种情况,少量的编码就可以实现需求。
1.编写自己的ExceptionMapper
import java.util.Locale; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * * @author Luo Wenqiang */ @Provider public class InvokeFaultExceptionMapper implements ExceptionMapper<InvokeFault> { public Response toResponse(InvokeFault ex) { StackTraceElement[] trace = new StackTraceElement[1]; trace[0] = ex.getStackTrace()[0]; ex.setStackTrace(trace); // System.out.println("处理自定义的异常"); ResponseBuilder rb = Response.status(Response.Status.INTERNAL_SERVER_ERROR); rb.type("application/json;charset=UTF-8"); rb.entity(ex); rb.language(Locale.SIMPLIFIED_CHINESE); Response r = rb.build(); return r; } }2.加载ExceptionMapper
<jaxrs:server id="services" address="/users"> <jaxrs:serviceBeans> <ref bean="userService"/> </jaxrs:serviceBeans> <jaxrs:providers> <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/> <bean class="org.fenbaoya.open.platform.users.InvokeFaultExceptionMapper"/> </jaxrs:providers> </jaxrs:server> 转载自:http://blog.163.com/java_star/blog/static/117714805201201333531865/