简体   繁体   English

Spring Rest Client 希望看到错误消息而不是异常

[英]Spring Rest Client want to see error message instead of exception

I have a spring rest client.我有一个春季休息客户。 when authentication details are not provided in the headers and I hit the service with当标头中未提供身份验证详细信息时,我点击了该服务

ResponseEntity<String> resp = restTemplate.exchange(url, HttpMethod.GET, request, String.class);

I get exception :我得到例外:

invoking error handler Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)在线程“main”org.springframework.web.client.HttpClientErrorException 中调用错误处理程序异常:401 未经授权在 org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)

But when I hit the url on mozilla browser, I get message like但是当我在 mozilla 浏览器上点击 url 时,我收到类似的消息

{"errors":[{"code":"xxxx","reason":"xxxx"}]}

Now here is what i want: i want to capture this error message in my code instead of getting 401 exception .现在这就是我想要的:我想在我的代码中捕获此错误消息,而不是获取 401 异常 I tried to see if there is anything in the response.我试图查看响应中是否有任何内容。 But the response received is null.但是收到的响应是空的。 How can I capture the error message received from the webservice ?如何捕获从网络服务收到的错误消息?

I feel odd to post answer for my own question. 我为自己的问题发布答案感到很奇怪。 But i finally achieved it through the following... 但是我终于通过以下方式实现了...

} catch (HttpClientErrorException e) {
      System.out.println(e.getStatusCode());
      System.out.println(e.getResponseBodyAsString());
    }

I was incorrectly searching for errors in response entity. 我错误地在响应实体中搜索错误。 But it is available in the exception. 但这是可用的例外。

If you use a global exception handler add the below method or check this如果您使用全局异常处理程序添加以下方法或检查此

https://www.javaguides.net/2018/09/spring-boot-2-exception-handling-for-rest-apis.html add below method in GlobalExceptionHandler class https://www.javaguides.net/2018/09/spring-boot-2-exception-handling-for-rest-apis.html在 GlobalExceptionHandler 类中添加以下方法

@ExceptionHandler({HttpClientErrorException.class, HttpStatusCodeException.class, HttpServerErrorException.class})
    @ResponseBody
    public ResponseEntity<Object> httpClientErrorException(HttpStatusCodeException e) throws IOException {
        BodyBuilder bodyBuilder = ResponseEntity.status(e.getRawStatusCode()).header("X-Backend-Status", String.valueOf(e.getRawStatusCode()));
        if (e.getResponseHeaders().getContentType() != null) {
            bodyBuilder.contentType(e.getResponseHeaders().getContentType());
        }
        return bodyBuilder.body(e.getResponseBodyAsString());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM