使用spring注释@ResponseStatus时,ResponseEntity中没有正文

时间:2016-12-15 10:59:49

标签: spring rest

我有一个使用spring注释抛出异常的端点,这是我的异常代码:

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class MyException extends BaseApiException{

public MyException (String variable){

super("variable :"+variable+" can not be updated.");
}
}

当我使用邮递员测试Rest端点时,我会得到一个具有正确状态代码的正确结果:

{
"errorType": "MyExption",
"message": "variable : XYZ can not be updated."
}

我的问题是当我尝试使用restTemplate调用服务时,我没有收到响应中的正文,这是我的代码:

ResponseEntity<Document> response;
RestTemplate restTemplate = new RestTemplate();
response = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entity, Document.class);

1 个答案:

答案 0 :(得分:1)

您需要定义一个错误处理程序来解压缩

public class MyResponseErrorHandler implements ResponseErrorHandler {
    private static final Logger log = LoggerFactory.getLogger(MyResponseErrorHandler.class);

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        //here you should be able to get //response.getBody()   
        log.error("Response error: {} {}", response.getStatusCode(), response.getStatusText());
    }

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        return isError(response.getStatusCode());
    }

    public static boolean isError(HttpStatus status) {
        HttpStatus.Series series = status.series();
    return (HttpStatus.Series.CLIENT_ERROR.equals(series)
            || HttpStatus.Series.SERVER_ERROR.equals(series));
   }


}


RestTemplate template = new RestTemplate();
template.setErrorHandler(new MyResponseErrorHandler());