如何使用ContainerRequestFilter中的JSON中止请求?

时间:2017-06-09 15:01:15

标签: java json java-ee jersey jax-rs

我想在错误上中止请求并返回JSON。但是下面的代码只返回一个字符串val res = withLock { lock => // some operation } (那不是我的消息)

如何通过JSON响应中止它?

"Unexpected 'U'"

1 个答案:

答案 0 :(得分:3)

看起来e.getMessage()无法为您提供有效的JSON。

一旦有效的JSON可以是带引号的字符串,您只需在异常消息中添加引号:

String message = "\"" + e.getMessage() + "\"";

requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(message)
                                 .type(MediaType.APPLICATION_JSON).build());

或者,您可以将消息包装到bean中:

public class ApiError {

    private String message;

    // Getters and setters
}

然后将其作为响应实体返回:

ApiError error = new ApiError();
error.setMessage(e.getMessage());

requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(error)
                                 .type(MediaType.APPLICATION_JSON).build());