【问题标题】:How abort request with JSON from ContainerRequestFilter?如何中止来自 ContainerRequestFilter 的 JSON 请求?
【发布时间】:2017-06-09 15:01:15
【问题描述】:

我想在出错时中止请求并返回 JSON。但是下面的代码只是返回一个字符串,上面写着"Unexpected 'U'"(这不是我的消息)

如何让它通过 JSON 响应中止?

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

【问题讨论】:

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


    【解决方案1】:

    看起来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());
    

    【讨论】:

    • 注意:对于 Jersey 1.x,您可以通过抛出 javax.ws.rs.WebApplicationException(javax.ws.rs.core.Response) 来中止。
    【解决方案2】:

    我扩展了其他有用的回复。

        import org.json.JSONObject;
    
    
        try {
        
        .  .  . 
    
        } catch (Exception e) {
            JSONObject json = new JSONObject();
            json.put("error-message", e.getMessage());
            json.put("status", "error");
            request.abortWith(
                    Response.status(Response.Status.UNAUTHORIZED)
                            .entity(json.toString())
                            .type(MediaType.APPLICATION_JSON_TYPE)
                            .build());
        }
    

    【讨论】:

      猜你喜欢
      • 2013-09-23
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多