CXF/ JAX-RS : Return Custom response from interceptor

自作多情 提交于 2019-11-30 19:04:02

I found a way to send a custom response from the interceptor but still can't figure out a way to call my CustomExceptionHandler from the interceptor

Code:

public void handleMessage(Message message) {

        MetadataMap<String, String> metadataMap = (MetadataMap<String, String>) message.get("jaxrs.template.parameters");

        if(null != metadataMap) {
            List<String> list = metadataMap.get("phoneNumber");
            if(null != list) {
                String phoneNumber = list.get(0);
                boolean result = validatePhoneNumber(phoneNumber);
                if(!result){
// Create a response object and set it in the message. 
// calling getExchange() will not call your service
                    Response response = Response
                .status(Response.Status.BAD_REQUEST)
                .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString()))
                .build();
        message.getExchange().put(Response.class, response);
// That's it
                }
            } else {
                Response response = Response
                .status(Response.Status.BAD_REQUEST)
                .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString()))
                .build();
        message.getExchange().put(Response.class, response);
            }
        } else {
            Response response = Response
                .status(Response.Status.BAD_REQUEST)
                .entity(new ErrorDetail(Response.Status.BAD_REQUEST.getStatusCode(), Response.Status.BAD_REQUEST.toString()))
                .build();
        message.getExchange().put(Response.class, response);
        }
    }

I raised a similar question on the cxf user group, see:

http://cxf.547215.n5.nabble.com/Handling-exceptions-in-a-JAX-RS-fault-interceptor-when-using-Local-Transport-td5733958.html

I ended up replacing my interceptors with ContainerRequestFilter and ContainerResponseFilter and then the Exception Mapper happily handled both application exceptions and exceptions thrown from the Filter.

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!