Servlet(Jersey2),以json格式从过滤器类发送错误消息

时间:2016-07-19 02:46:42

标签: servlets jersey jax-rs servlet-filters

    ObjectMapper mapper = new ObjectMapper();
        String jsonInString = mapper.writeValueAsString(erresp);
        svltresp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        svltresp.setContentType("application/json");
        PrintWriter writer = svltresp.getWriter();
        writer.println(jsonInString);

我不确定这是不是最好但是找不到方法。

我正在开发Jersey2应用程序。

这是我的错误模型类

@XmlRootElement(name =“ErrorResponse”) 公共类ErrorResponse {

@XmlElement
private String errorInstanceId;

@XmlElement
private String errorCode;

@XmlElement
private String errorMessage;

@XmlElement
private String errorAdditionalDescription;

public String getErrorInstanceId() {
    return errorInstanceId;
}

public void setErrorInstanceId(String errorInstanceId) {
    this.errorInstanceId = errorInstanceId;
}

public String getErrorCode() {
    return errorCode;
}

public void setErrorCode(String errorCode) {
    this.errorCode = errorCode;
}

public String getErrorMessage() {
    return errorMessage;
}

public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
}

public String getErrorAdditionalDescription() {
    return errorAdditionalDescription;
}

public void setErrorAdditionalDescription(String errorAdditionalDescription) {
    this.errorAdditionalDescription = errorAdditionalDescription;
}

public ErrorResponse() {
}

public ErrorResponse(String errorInstanceId, String errorCode, String errorMessage, String errorAdditionalDetails) {
    this.errorInstanceId = errorInstanceId;
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
    this.errorAdditionalDescription = errorAdditionalDetails;
}

}

我正在json发送错误消息

ErrorResponse errorResponse = new ErrorResponse(UUID.randomUUID().toString(), "error",
                "Failed", null);
        throw new WebApplicationException(Response.status(400).entity(errorResponse).build());

但问题是,

当我在servlet中编写源代码时,它工作正常,我可以看到json格式的错误,但是,当我在过滤器类中编写时,我只能在普通的apache html错误页面中看到。

有人能解释一下这里发生了什么,并建议我解决方案吗?

提前致谢

1 个答案:

答案 0 :(得分:0)

当从资源或servlet抛出异常时,根据@Produces中的MIME media type,将相应地生成响应。

如果从过滤器(外部资源)抛出异常,我们应该将media type显式添加到响应对象。

Response.ResponseBuilder response = Response.status(400).entity(errorResponse);
response = response.type(MediaType.APPLICATION_JSON);
throw new WebApplicationException(response.build());