RestTemplate 尝试捕获

RestTemplate try catch

我正在使用下面的 Java (Spring 2.0) 代码从网络服务读取 ResponseEntity:

public ResponseEntity<?> getTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<?> myResponse= restTemplate.postForEntity(
            myUrl, 
            myRequestObj, 
            MyResponseObj.class);
            
    return myResponse;
}

但是,如果 myUrl 网络服务 returns HttpStatus.BAD_REQUEST (400) ,这不会分配给 myResponse 并引发错误,因此没有 ResponseBody,我需要将请求包装在一个 try catch 块。这是正确的还是有办法解决这个问题? 此外,这是否意味着 myUrl Web 服务永远不应有意(以编程方式)将 myResponseObj 的 HttpStatus 设置为 HttpStatus.BAD_REQUEST?因此,即使 myRequestObj 包含错误数据,myUrl webService 仍应将响应状态设置为 200 左右的值,即 HttpStatus.NO_CONTENT。欢迎就如何正确执行此操作提出任何意见。

Is this correct or is there a way round this?

您描述的行为由 spring 的默认错误处理程序定义,如果状态代码在 400-499 范围内,则抛出 HttpClientErrorExceptionHttpServerErrorException如果状态代码在 500-599 范围内,如果状态代码未知,则为 UnknownHttpStatusCodeException。要处理此类错误代码,您可以捕获异常或按照 here.

所述注册自定义异常处理程序

Also, does this mean that the myUrl webservice should never intentionally (programatically) set the HttpStatus of myResponseObj to HttpStatus.BAD_REQUEST?

根据 RFC 7231,状态代码 400 用于指示服务器不能或不会处理请求,因为客户端在创建请求时出错(例如,格式错误的请求语法, 非法请求 消息框架或欺骗性请求路由)。因此,您可以自由使用该状态代码向客户端指示此类行为。