针对HTTP错误的POJOMappingFeature?

时间:2013-04-23 09:47:02

标签: google-app-engine jersey jax-rs

我将com.sun.jersey.api.json.POJOMappingFeature设置为true,它适用于HTTP 200响应。

但是,当我的应用程序返回错误时,它会显示带有错误标题的text / html响应。

即使我像这样创建自定义异常(在ContainerRequestFilter中):

throw new WebApplicationException(
    Response.status(Response.Status.FORBIDDEN)
      .type(MediaType.APPLICATION_JSON)
      .build()
);

它仍显示通用text / html 403错误。

1 个答案:

答案 0 :(得分:2)

您应该尝试来自Jersey的ExceptionMapper:

首先,您的自定义例外:

public class UnauthorizedException extends RuntimeException {
   public UnauthorizedException() {}
}

然后,您的实体,您要发回:

@XmlRootElement
public class ErrorMessage{
  @XmlElement
  private String message;

  public ErrorMessage(String message){
    this.message = message;
  }
}

最后,魔术开始了:)

@Provider
public class UnauthorizedExceptionMapper implements ExceptionMapper<UnauthorizedException>{

  @Override
  public Response toResponse(UnauthorizedException exception) {
    return Response.status(Response.Status.UNAUTHORIZED)
                   .entity(new ErrorMessage("Not Authorized"))
                   .build();
   }
 }

现在,

时应该返回JSON-Entity
throw new UnauthorizedException();

此致

相关问题