我有一个用 Java 编写的 Spring Boot 应用程序,它是一个 REST API。该服务 (Svc A) 调用 REST API 服务 (Svc B),该服务也是用 Java 编写的 Spring Boot 应用程序。当未找到数据时,Svc B 返回 404 状态代码。我需要将此响应更改为 200 状态代码并返回一个空响应对象。我不确定是否或如何执行此操作。
我可以捕获错误并确定 404 是否是“找不到数据”错误。但是,我不知道如何将响应更改为 200 空响应。 我正在使用 FeignClient 来调用该服务。这是捕获 404 的错误代码:
@Component
public class FeignErrorDecoder implements ErrorDecoder {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public Exception decode(String methodKey, Response response) {
Reader reader = null;
String messageText = null;
switch (response.status()){
case 400:
logger.error("Status code " + response.status() + ", methodKey = " + methodKey);
case 404:
{
logger.error("Error took place when using Feign client to send HTTP Request. Status code " + response.status() + ", methodKey = " + methodKey);
try {
reader = response.body().asReader();
//Easy way to read the stream and get a String object
String result = CharStreams.toString(reader);
logger.error("RESPONSE BODY: " + result);
ObjectMapper mapper = new ObjectMapper();
//just in case you missed an attribute in the Pojo
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//init the Pojo
ExceptionMessage exceptionMessage = mapper.readValue(result,
ExceptionMessage.class);
messageText = exceptionMessage.getMessage();
logger.info("message: " + messageText);
} catch(IOException ex) {
logger.error(ex.getMessage());
}
finally {
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new ResponseStatusException(HttpStatus.valueOf(200), messageText);
}
default:
return new Exception(response.reason());
}
}
}
我可以将状态代码更改为 200,它会返回 200,但我需要响应有一个空响应对象。 上面的代码将返回错误响应对象的响应正文:
{
"statusCd" : "200",
"message" : "The Location not found for given Location Number and Facility Type Code",
"detailDesc" : "The Location not found for given Location Number and Facility Type Code. Error Timestamp : 2020-01-31 18:19:13"
}
我需要它返回这样的响应正文: 200 - 空响应
{
"facilityNumber": "923",
"facilityTimeZone": null,
"facilityAbbr": null,
"scheduledOperations": []
}
最佳答案
如果出现 404 错误,请尝试
return new ResponseStatusException(HttpStatus.valueOf(200));
关于java - 将 REST API 的 404 响应更改为 200 空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60081744/