问题描述
我有两个微服务.第一个接收来自前端的调用,然后调用第二个 uService 以接收一些数据.最后是返回错误响应(错误请求,这没关系 - 这是一个用例).但是,我丢失了从第二个微服务返回的正文(消息),因为第一个在调用中抛出 HttpClientErrorException 400 null
I have two microservices. The first one receives a call from the Frontend and then it calls to the second uService to receive some data. The last is returning an error response (Bad Request, this is ok - it is a use-case). However, I am losing the body (message) returned from the second microservice, as the first is throwing a HttpClientErrorException 400 null in the call
这是我的代码:
ResponseEntity<MyEntity> entityResponse = restTemplate.getForEntity(url, MyEntity.class, id);
由于抛出异常,我无法执行 entityResponse.getStatusCode()
.
I am not able to do entityResponse.getStatusCode()
as an exception is thrown.
在 ControllerAdvice 中处理它,即使我从服务返回自定义消息,我的异常消息也是400 null".
Handled it in the ControllerAdvice, my exception message is "400 null" even I return a custom message from the service.
所以,我想得到被调用的uservice中发送的响应消息来管理它.
So, I would like to get the response message sent in the called uservice to manage it.
提前致谢.
推荐答案
这里解释如何捕获异常和访问正文的答案是正确的.但是,您可以使用不同的方法.您可以使用发送 Http 请求并处理响应的 3-d 方库.著名的产品之一是 Apache commons HTTPClient:HttpClient javadoc, HttpClient Maven 工件.有一个鲜为人知但更简单的 HTTPClient(我编写的开源 MgntUtils 库的一部分):MgntUtils HttpClient javadoc、MgntUtils maven artifact、MgntUtils Github.使用这些库中的任何一个,您都可以作为业务逻辑的一部分独立于 Spring 发送 REST 请求和接收响应
The answers here that explain how to catch the exception and access the body are correct. However, you may use a different approach. You can use a 3-d party library that sends Http request and handles the response. One of the well-known products would be Apache commons HTTPClient: HttpClient javadoc, HttpClient Maven artifact. There is by far less known but much simpler HTTPClient (part of an open source MgntUtils library written by me): MgntUtils HttpClient javadoc, MgntUtils maven artifact, MgntUtils Github. Using either of those libraries you can send your REST request and receive response independently from Spring as part of your business logic
这篇关于HttpClientErrorException 400 null 在微服务中使用 RestTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!