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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26404381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:52:55  来源:igfitidea点击:

Spring Rest Client want to see error message instead of exception

javaspringrestresttemplate

提问by Amar

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. 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 ?

现在这就是我想要的:我想在我的代码中捕获此错误消息,而不是获取 401 异常。我试图查看响应中是否有任何内容。但是收到的响应是空的。如何捕获从网络服务收到的错误消息?

回答by Amar

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.

我错误地搜索响应实体中的错误。但它在异常中可用。