使用XML或JSON的JAX-RS(Jersey)自定义异常

Osk*_*kar 44 java mime jax-rs jersey

我有一个使用Jersey构建的REST服务.

我希望能够根据发送到服务器的MIME设置我的自定义异常编写器的MIME.application/json收到json application/xml时,以及收到xml 时返回.

现在我硬编码application/json,但这使得XML客户端陷入了困境.

public class MyCustomException extends WebApplicationException {
     public MyCustomException(Status status, String message, String reason, int errorCode) {
         super(Response.status(status).
           entity(new ErrorResponseConverter(message, reason, errorCode)).
           type("application/json").build());
     }
}
Run Code Online (Sandbox Code Playgroud)

我可以利用什么上下文来获取当前请求Content-Type

谢谢!


根据答案更新

对于任何对完整解决方案感兴趣的人:

public class MyCustomException extends RuntimeException {

    private String reason;
    private Status status;
    private int errorCode;

    public MyCustomException(String message, String reason, Status status, int errorCode) {
        super(message);
        this.reason = reason;
        this.status = status;
        this.errorCode = errorCode;
    }

    //Getters and setters
}
Run Code Online (Sandbox Code Playgroud)

和一起 ExceptionMapper

@Provider
public class MyCustomExceptionMapper implements ExceptionMapper<MyCustomException> {

    @Context
    private HttpHeaders headers;

    public Response toResponse(MyCustomException e) {
        return Response.status(e.getStatus()).
                entity(new ErrorResponseConverter(e.getMessage(), e.getReason(), e.getErrorCode())).
                type(headers.getMediaType()).
                build();
    }
}
Run Code Online (Sandbox Code Playgroud)

其中ErrorResponseConverter是自定义JAXB POJO

Bry*_*Luk 25

您可以尝试将@javax.ws.rs.core.Context javax.ws.rs.core.HttpHeaders字段/属性添加到根资源类,资源方法参数或自定义javax.ws.rs.ext.ExceptionMapper并调用HttpHeaders.getMediaType().


Dom*_* D. 15

headers.getMediaType()以实体的媒体类型响应,而不是Accept标头.转换异常的适当方法是使用Accept标头,以便客户端以他们请求的格式获取响应.鉴于上述解决方案,如果您的请求如下所示(注意JSON接受标头,但是XML实体),您将获得XML.

POST http://localhost:8080/service/giftcard/invoice?draft=true HTTP/1.1
Accept: application/json
Authorization: Basic dXNlcjp1c2Vy
Content-Type: application/xml
User-Agent: Jakarta Commons-HttpClient/3.1
Host: localhost:8080
Proxy-Connection: Keep-Alive
Content-Length: 502
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><sample><node1></node1></sample>

使用Accept标头再次正确实现:

public Response toResponse(final CustomException e) {
    LOGGER.debug("Mapping CustomException with status + \"" + e.getStatus() + "\" and message: \"" + e.getMessage()
            + "\"");
    ResponseBuilder rb = Response.status(e.getStatus()).entity(
            new ErrorResponseConverter(e.getMessage(), e.getReason(), e.getErrorCode()));

    List<MediaType> accepts = headers.getAcceptableMediaTypes();
    if (accepts!=null && accepts.size() > 0) {
        //just pick the first one
        MediaType m = accepts.get(0);
        LOGGER.debug("Setting response type to " + m);
        rb = rb.type(m);
    }
    else {
        //if not specified, use the entity type
        rb = rb.type(headers.getMediaType()); // set the response type to the entity type.
    }
    return rb.build();
}
Run Code Online (Sandbox Code Playgroud)