带有请求消息的Apache CXF ExceptionMapper

时间:2014-09-23 23:37:23

标签: java rest exception exception-handling cxf

我想知道这样的事情是否可行,或者是否有更好的方法:

public class WebServiceExceptionMapper implements ExceptionMapper<Exception> {

  private static Logger logger = LoggerFactory.getLogger(WebServiceExceptionMapper.class);

  @Override
  public Response toResponse(Exception ex, Message requestMessage) {
    logger.error("request=" + httpMessage.etc..etc.., ex);
    return Response.status(Status.INTERNAL_SERVER_ERROR).build();
  }

}

基本上我希望不仅能够记录异常,还能记录触发错误的请求消息。更具体地说,如果请求包含JSON或XML,我想抓住它。

1 个答案:

答案 0 :(得分:0)

NVM。通过在我的ExceptionMapper中注入MessageContext并添加如下所述的自定义RequestHandler来计算它:http://cxf.547215.n5.nabble.com/Accessing-JAXRS-JSON-content-directly-td4390185.html

public class StringContentRequestHandler implements RequestHandler { 

private static final Logger logger = LoggerFactory.getLogger(RawContentRequestHandler.class); 

public Response handleRequest(Message m, ClassResourceInfo resourceClass) { 
    InputStream is = m.getContent(InputStream.class); 
    try { 
        CachedOutputStream bos = new CachedOutputStream(); 
        IOUtils.copy(is, bos); 

        bos.flush(); 
        is.close(); 

        m.setContent(InputStream.class, bos.getInputStream()); 
        StringBuilder builder = new StringBuilder(); 
        bos.writeCacheTo(builder, "utf-8"); 
        m.setContent(String.class, builder.toString()); 
        return null; 

    } catch (IOException ex) { 
        logger.error("IOException on getting raw content", ex); 
        return null; 
    } 
} 
}