1

使用 Resteasy 框架编写 Web 服务。

如果在服务器上处理时抛出任何异常,需要使用 HTTP 500 响应向客户端发送错误消息。

我在 WebService 接口中有 void 方法:

public interface WebLocationService {

@DELETE
@Path("/delete")
   @Consumes(MediaType.APPLICATION_JSON)
   public void deleteLocation(LocationId locationId); { }

如果此方法抛出任何异常,则 ExceptionMapper 将捕获它并返回带有 500 状态和异常消息作为实体的响应。

public class WebApplicationExceptionMapper implements                 
                                     ExceptionMapper<WebApplicationException>{

@Override
public Response toResponse(WebApplicationException e) {
    return Response.serverError().entity(e.getMessage()).build();
} }

使用 Resteasy 客户端代理框架。

对于 500 状态的响应,客户端代理框架抛出 ServerErrorException 并用它包装响应。从 ServerErrorException 获取响应。当我在响应中调用 readEntity 或 getEntity 时,它会抛出带有 IllegalStateException 的响应关闭错误。

调试后发现,基于web服务接口方法返回类型,代理框架决定EntityExtractor。

1)对于 void 返回类型,DefaultEntityExtractor$3 缓冲实体输入流,然后关闭响应。

2)对于 Response、Response.Status 和 ResponseObject,DefaultEntityExtractor$1,$2,$4 不关闭响应。

3)对于任何其他类型,BodyEntityExtractor 是实体提取器,不关闭响应。

4

0 回答 0