Получить сообщение об ошибке из ResponseStatusException с ResponseErrorHandler - PullRequest
0 голосов
/ 16 мая 2019

У меня есть 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, я не могу найти «My error msg», кажется, что его нет в объекте. Есть ли способ получить сообщение?

Thx

1 Ответ

0 голосов
/ 16 мая 2019

Перехват 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();
        }
...