使用ResponseErrorHandler从ResponseStatusException获取错误消息

时间:2019-05-16 07:50:19

标签: spring-boot resttemplate

我有一个API,在发生错误的情况下会抛出ResponseStatusException:

throw new ResponseStatusException(HttpStatus.NOT_FOUND, "My error msg");

在客户端,我有:

RestTemplate restTemplate = this.builder.errorHandler(new RestTemplateResponseErrorHandler()).build();
// Then I use restTemplate to call URLs with restTemplate.exchange(...)

还有ResponseErrorHandler:

@Component
public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {
 @Override
    public boolean hasError(ClientHttpResponse httpResponse) throws IOException {

        return (httpResponse.getStatusCode().series() == HttpStatus.Series.CLIENT_ERROR || httpResponse.getStatusCode()
            .series() == HttpStatus.Series.SERVER_ERROR);
    }

    @Override
    public void handleError(ClientHttpResponse httpResponse) throws IOException {

        String error = new String(httpResponse.getBody().readAllBytes(), StandardCharsets.UTF_8);

    }
}

问题是getBody()为空,当我检查httpResponse时,找不到“我的错误消息”,似​​乎该对象中不存在该消息。 有什么方法可以获取味精吗?

Thx

2 个答案:

答案 0 :(得分:0)

您需要像这样使用RestTemplateBuilder构建RestTemplate实例:

public class xyz {

RestTemplate restTemplate;

    @Autowired
    public xyz(RestTemplateBuilder restTemplateBuilder) {
        restTemplate = restTemplateBuilder
          .errorHandler(new RestTemplateResponseErrorHandler())
          .build();
    }
}

答案 1 :(得分:-1)

捕获HttpClientErrorException如下:

try{
            HttpEntity<ProfileDto> entity = new HttpEntity<ProfileDto>(profileDto,headers);
            response= restTemplate.postForEntity(environment.getProperty("app.filedownload.url"),entity, xxxxxx.class);
        }catch(HttpClientErrorException | HttpServerErrorException  e ){
            if(HttpStatus.UNAUTHORIZED.equals(e.getStatusCode())){
            //do your stufs
            }
        }catch(Exception  e){
            e.printStackTrace();
        }