RestTemplate 抛出通用 400 错误请求,但自定义服务器发送的消息不会丢失

See*_*ker 0 java spring resttemplate spring-boot

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

如果我们从邮递员调用此 API,我们会看到相应的错误。

然而,当我们使用 Spring 的 RestTemplate 在其他应用程序的调用者方法中调用此方法时,我们看到的只是一个带有空正文的 400 Bad 请求。没有看到错误消息。

这里可能有什么问题。我们如何获取 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);
Run Code Online (Sandbox Code Playgroud)

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

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


    public InvalidDataException(String msg) {
        super(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)

控制器看起来像

@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");
}
Run Code Online (Sandbox Code Playgroud)

Muk*_*sal 7

Spring 的 RestTemplate 实现有一种奇怪的功能。每当响应是 4XX 时,它都会抛出 aHttpClientErrorException而不是返回响应。同样,当响应是 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;
    }
Run Code Online (Sandbox Code Playgroud)