我有一个用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));