【问题标题】:RestTemplate throwing generic 400 Bad Request, but custom server sent message is not is lostRestTemplate 抛出通用 400 错误请求,但自定义服务器发送的消息不会丢失
【发布时间】:2019-05-28 17:02:09
【问题描述】:

我们有一个带有 POST 映射的 rest 控制器 API,它将一个对象作为请求参数并在 DB 上创建它。我们对输入对象的验证很少,如果有任何错误,那么我们会抛出异常并带有自定义消息。

如果我们从 post man 调用此 API,我们会看到相应的错误。

而当我们在其他应用程序的调用者方法中使用 Spring 的 RestTemplate 调用它时,我们看到的只是一个 400 Bad request 和空主体。没有看到错误消息。

这可能是什么问题。我们如何获取 API 抛出的自定义消息。

这是我们如何使用 rest 模板调用 API。

    String url = "https://localhost:8895/servuceUrl";
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<AddRequest> entity = new HttpEntity<AddRequest>(obj, headers);
    ResponseEntity<String> data = null;
    adddata = restTemplate.exchange(syncurl, HttpMethod.POST, entity, String.class);

在服务器端我们有一个异常写成

@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public class InvalidDataException extends Exception {


    public InvalidDataException(String msg) {
        super(msg);
    }
}

控制器的样子

@PostMapping(RestUriMappings.POST_MAPPING)
public ResponseDto add(@Valid @RequestBody AddRequest data) throws InvalidDataException 
{

    logger.debug("Incoming data for add: {}", data.toString());

    // validate the payload
    if(data.getName()==null)
       throw new InvalidDataException("Name shouldnt be null");
}

【问题讨论】:

  • 你试过调用 String body = data.getBody() 吗?身体还是空的吗?
  • 你在POSTMAN中是否也设置了相同的媒体类型标头?

标签: java spring spring-boot resttemplate


【解决方案1】:

Spring 的 RestTemplate 实现有一种奇怪的功能。每当响应为 4XX 时,它会抛出 HttpClientErrorException 而不是返回响应。同样,当响应是 5XX 响应时,它会抛出 HttpServerErrorException

当您进入库时,您会在DefaultResponseErrorHandler.java#handleError(ClientHttpResponse response) 中看到负责此类功能的一段代码。

因此,如果您想获取原始的 4XX 或 5XX 响应,则必须在 RestTemplate.java#exchange() 方法上编写一个包装器。像这样的东西-

private ResponseEntity<String> exchange(String url, HttpMethod method, HttpEntity<?> httpEntity,
                                           Class<?> class1, Map<String, String> paramMap) {
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(url, method, httpEntity, String.class, paramMap);
        }catch(HttpClientErrorException e) {
            responseEntity = new ResponseEntity<>(e.getResponseBodyAsString(), HttpStatus.BAD_REQUEST);
        }catch(HttpServerErrorException e) {
            responseEntity = new ResponseEntity<>(e.getResponseBodyAsString(), HttpStatus.INTERNAL_SERVER_ERROR);
            throw e;
        }catch(Exception e) {
            responseEntity = new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            throw e;
        }
        return responseEntity;
    }

【讨论】:

    【解决方案2】:

    你不见了:

    headers.setContentType(MediaType.APPLICATION_JSON);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 2016-09-17
      • 2013-10-02
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多