Bean Validation 400 errors are returning default error page (html) instead of Response entity (json)

China☆狼群 提交于 2019-12-19 03:37:24

问题


I have a JUnit testsuite: GrizzlyHttpServerFactory + Jersey + Bean Validation (jersey-container-grizzly2-servlet/jersey-bean-validation ver 2.12, grizzly-http-server ver 2.3.16, hibernate-validator ver 5.0.0.Final)

The 400 errors generated by a ValidationException are returning Grizzly's default error page (html) instead of the Bean Validation's Response entity (json). I've tried a ClientResponseFilter and its entityStream also contains the html error page.

When I run the system under Tomcat, the ValidationExceptions return a Response with a json-formatted entity.

Any ideas on how to configure Grizzly/Jersey/Validator to NOT return the error page (html) and put the ValidationExceptions into the Response's entityStream, just like Tomcat?

Thanks in advance,

Mike Norman


回答1:


After looking into the code to which alexey pointed to for Jersey 2.13, I found out that the code path in question can be avoided by setting the property jersey.config.server.response.setStatusOverSendError to "true".

So, as a workaround until JERSEY-2673 is fixed, I just placed property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true"); into my ResourceConfig class and was able to see the custom error responses in the browser.




回答2:


I went throw Jersey code and looks like it's the way Jersey works and IMO it's just a coincidence that it works fine on Tomcat. Jersey processes the validation (and probably not only validation) errors following way:

  1. org.glassfish.jersey.message.internal.CommittingOutputStream#flushBuffer(boolean)

    writes JSON error message to the Servlet OutputStream;

  2. org.glassfish.jersey.servlet.internal.ResponseWriter#commit()

    calls HttpServletResponse#sendError(int, String), that according to the Servlet spec:

    ... If data has been written to the response buffer, but not returned to the client (i.e. the response is not committed), the data in the response buffer must be cleared and replaced with the data set by these methods ...

    So Grizzly clears up buffer with the JSON error and replaces it with the default error page.

I'd suggest to file an issue @ Jersey issue tracker https://java.net/jira/browse/JERSEY



来源:https://stackoverflow.com/questions/25755773/bean-validation-400-errors-are-returning-default-error-page-html-instead-of-re

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