【问题标题】:Ho to set status code 400 in response object如何在响应对象中设置状态码 400
【发布时间】:2020-01-25 06:28:50
【问题描述】:

我正在使用来自 javax.ws.rs-api 的 Response 对象,即使我可以设置像 Response.status(Response.status.BAD_REQUEST).build() 这样的状态,返回的响应代码始终是 200 并带有响应正文包含表示 BAD_REQUEST 的 statusInfo 参数。 有没有办法根据服务器端的一些输入验证将响应代码设置为 400?

【问题讨论】:

    标签: java api error-handling response


    【解决方案1】:

    这对我有用,我测试过。

     @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getTestResult() {
        logger.info("Requested Test Service");
        try {
            Object result = "";[enter image description here][1]
          return  Response.status(Response.Status.BAD_REQUEST)
                  .entity(result).build();
        } catch (Exception e) {
            return Response.ok("error", e.getMessage()).build();
        }
    
    }
    

    【讨论】:

    • 感谢您的回答,但是当我使用 swagger/postman 进行测试时,我的响应状态为 200
    【解决方案2】:

    不只是设置响应状态,而是从服务层抛出错误并让它传播到控制器。 在控制器中你可以有类似的东西

    @Controller
    public class MyService {
        @RequestMapping(value = "your api url path", method = RequestMethod.GET, produces = "application/
        public Response jsonAccounts(HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            return Response.status(Response.Status.BAD_REQUEST).entity("Bad request received").build();
        }
    
        @ExceptionHandler(MyBadException.class)
        @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Bad request Request Exception")
        public void unexpectedError(HttpServletRequest request, Exception 
            log.debug("return HttpStatus.BAD_REQUEST, unexpectedError due to Exception", e);
        }
    }
    

    【讨论】:

    • 不确定 OP 是否使用 Spring 框架。答案仅适用于基于 Spring 的应用程序。
    • 在您的示例中,流程是这样的:由 jsonAccounts() 处理的请求 -> 进行服务调用 -> 服务引发错误 -> 控制器的意外错误()处理错误?
    • 是的@ShashankSinghal,但正如 Prashant 提到的,它只适用于 Spring
    • 控制器的 jsonAccounts() 方法有没有办法在不使用@ResponseStatus 标签的情况下设置响应状态?
    • @RahulAgrawal 感谢您的更新,但是当我使用 swagger/postman 进行相同测试时,响应状态始终为 200(因此是我的原始问题),但响应正文包含 statusInfo 参数,其中显示 BAD_REQUEST。
    猜你喜欢
    • 2020-04-20
    • 2021-07-21
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2015-04-20
    相关资源
    最近更新 更多