简体   繁体   English

当资源引发异常时,RestEasy重置所有标头

[英]RestEasy resets all headers when resource throws an exception

I've uncovered something strange while using resteasy-jaxrs in a Cors enabled jBoss server. 在启用了Cors的jBoss服务器中使用resteasy-jaxrs时,我发现了一些奇怪的东西。 Here's the setup: 设置如下:

Our server has thetransactioncompany.com's CorsFilter (v1.3.2) enabled as a servlet filter to enable CORS and add the appropriate CORS headers to the HttpServletResponse object. 我们的服务器启用了transactioncompany.com的CorsFilter(v1.3.2)作为Servlet过滤器,以启用CORS并将适当的CORS标头添加到HttpServletResponse对象。

The server itself is using resteasy-jaxrs (v2.3.2.Final) to serve JSON endpoints to power our app, obviously running on a separate domain. 服务器本身正在使用resteasy-jaxrs(v2.3.2.Final)来提供JSON终结点来为我们的应用程序提供动力,显然是在单独的域上运行。

The issue is that if one of my endpoint methods generates any type of exception (NPE, UnauthorizedException, InternalServerErrorException), as a part of preparing the response, RestEasy makes the call 问题是,如果我的一种端点方法生成任何类型的异常(NPE,UnauthorizedException,InternalServerErrorException),作为准备响应的一部分,RestEasy会进行调用

(HttpServletResponse)response.reset() 

which clears out my CORS headers. 清除我的CORS标头。 This causes Chrome to rightly act as if the request should be canceled. 这会导致Chrome正确执行操作,就好像应该取消请求一样。 This is really inconvenient for my front end dev who needs those error codes. 这对于需要这些错误代码的前端开发人员真的很不方便。

Two questions: 两个问题:

  1. Why would RestEasy want to clear those headers? 为什么RestEasy要清除这些标题?
  2. Has anyone else run across this and have any workarounds? 还有其他人遇到这个问题并且有任何解决方法吗?

I am actually surprised to see that you have encountered this behavior since I've never seen it, and I certainly have generated plenty of exceptions in my day. 自从我从未见过这种行为以来,我真的感到很惊讶,而且我当然也创造了很多例外。

Regardless, consider writing a custom ExceptionMapper as described here . 无论如何,请考虑按照此处所述编写自定义ExceptionMapper You can populate the response with your CORS headers and return it from toResponse along with the appropriate error information. 您可以使用CORS标头填充响应,并将其与适当的错误信息一起从toResponse返回。

I ran into this issue too, and I had a workaround by using a response wrapper 我也遇到了这个问题,并且使用响应包装器解决了问题

class CorsHeaderResponseWrapper extends HttpServletResponseWrapper{

    public CorsHeaderResponseWrapper(HttpServletResponse resp) {
        super(resp);
        setCorsHeader();
    }

    void setCorsHeader(){
        HttpServletResponse resp = (HttpServletResponse)getResponse();
        //set cors header here
    }

    public void reset(){
        super.reset();
        //set again if anyone reset it
        setCorsHeader();
    }

}

when calling doFilter 调用doFilter时

chain.doFilter(req, new CorsHeaderResponseWrapper(resp));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM