[英]Spring WebClient - how to access response body in case of HTTP errors (4xx, 5xx)?
[英]Prevent Tomcat from interfering with Jersey/JAX-RS 2 Response Body on HTTP Error Status 4xx or 5xx
我有一個REST API的以下堆棧
我的目標是在發生錯誤時擁有自定義響應主體。 我希望能夠向客戶端發送一個解釋,以便更容易調試。
首先我嘗試使用@Context HttpServletResponse
並在那里設置http狀態代碼,但是被澤西忽略了(這是正常行為,但這超出了我的理解)
然后我嘗試使用像這樣的WebApplicationException
:
@GET
@Path("/myapi")
public BaseResponse getSomething() {
BaseResponse b = new BaseResponse();
if(error) {
b.setStatusDescription("reason for error");
throw new WebApplicationException(Response.status(Response.Status.CONFLICT).entity(b).build());
}
//add content to BaseReponse
return b
}
但是Tomcat給我的回報是這樣的:
<html>
<head>
<title>Apache Tomcat/7.0.47 - Error report</title>
<style>
<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22p
這是標准的Tomcat HTML輸出通過響應體的contet長度上限我想回去( .entity(b)
-的長度b
)。 所以它被認可,但Tomcat只是用自己的錯誤頁面覆蓋它。
作為旁注,我也嘗試以相同的結果返回Response:
return Response.status(Response.Status.CONFLICT).entity(b).build()
那么我如何告訴Tomcat讓我一個人讓自己的回答通過?
只需在ResourceConfig類的配置中添加以下代碼即可。
property(ServerProperties.RESPONSE_SET_STATUS_OVER_SEND_ERROR, "true");
問題是我使用的是來自ehcache的GzipServlet,它似乎不適用於球衣。 在多個階段期間,響應包裝器拋出異常。
這是ehcache的依賴:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-web</artifactId>
<version>2.0.4</version>
</dependency>
以及web.xml中有問題的servlet定義
<filter>
<filter-name>GzipFilter</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.GzipFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>/rest/*</url-pattern>
</filter-mapping>
作為替代方案我現在使用Jetty Servlet: http : //download.eclipse.org/jetty/stable-9/apidocs/org/eclipse/jetty/servlets/GzipFilter.html
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlets</artifactId>
<version>8.1.0.RC5</version>
</dependency>
web.xml中
<filter>
<filter-name>GzipFilter</filter-name>
<filter-class>org.eclipse.jetty.servlets.GzipFilter</filter-class>
<init-param>
<param-name>mimeTypes</param-name>
<param-value>text/html,text/plain,text/xml,application/xhtml+xml,text/css,application/javascript,image/svg+xml</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>GzipFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
免責聲明:是的我知道我可以在tomcat配置中激活gzip,但我正在編寫一個必須能夠擁有和不使用gzip的端點的測試服務器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.