gpt4 book ai didi

java - 无法在 Spring 返回带有异常详细信息的 ResponseEntity

转载 作者:搜寻专家 更新时间:2023-10-31 19:59:31 25 4
gpt4 key购买 nike

我已经创建了一个 Spring Restful 服务和 Spring MVC 应用程序。

Restful 服务::如果 Restful 服务存在于数据库中,则返回一个实体。如果不存在则在 ResponseEntity 对象中返回一个自定义的 Exception 信息。

使用 Postman 测试,它按预期工作。

@GetMapping(value = "/validate/{itemId}", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<MyItem> validateItem(@PathVariable Long itemId, @RequestHeader HttpHeaders httpHeaders) {

MyItem myItem = myitemService.validateMyItem(itemId);
ResponseEntity<MyItem> responseEntity = null;
if (myItem == null) {
throw new ItemNotFoundException("Item Not Found!!!!");
}
responseEntity = new ResponseEntity<MyItem>(myItem, headers, HttpStatus.OK);
return responseEntity;
}

如果请求的实体不存在,Restful Service 返回如下。

@ExceptionHandler(ItemNotFoundException.class)
public ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {
System.out.println("In CREEH::ItemNFE");
ExceptionResponse exceptionResponse = new ExceptionResponse("Item Not Found Ex!!!", new Date(), webRequest.getDescription(false));
ResponseEntity<ExceptionResponse> responseEntity = new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_FOUND);
return responseEntity;
}

但是当我使用 RestTemplate 从 spring MVC 应用程序调用上述服务时,它返回一个有效对象(如果存在)。

如果请求的对象不存在,Restful 服务将返回异常信息,但它不会到达调用(spring MVC)应用程序。

Spring MVC应用使用Rest模板调用Restful Web Service

String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class, uriParms);
int restCallStateCode = responseEntity.getStatusCodeValue();

最佳答案

这是预期的行为。当http状态为客户端错误或服务器错误时,Rest模板抛出异常,当http状态不是错误状态时返回响应。

您必须提供实现才能使用您的错误处理程序,将响应映射到响应实体并抛出异常。

使用 ResponseEntity 字段创建新的错误异常类。

public class ResponseEntityErrorException extends RuntimeException {
private ResponseEntity<ErrorResponse> errorResponse;
public ResponseEntityErrorException(ResponseEntity<ErrorResponse> errorResponse) {
this.errorResponse = errorResponse;
}
public ResponseEntity<ErrorResponse> getErrorResponse() {
return errorResponse;
}
}

将错误响应映射回 ResponseEntity 的自定义错误处理程序。

public class ResponseEntityErrorHandler implements ResponseErrorHandler {

private List<HttpMessageConverter<?>> messageConverters;

@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return hasError(response.getStatusCode());
}

protected boolean hasError(HttpStatus statusCode) {
return (statusCode.is4xxClientError() || statusCode.is5xxServerError());
}

@Override
public void handleError(ClientHttpResponse response) throws IOException {
HttpMessageConverterExtractor<ExceptionResponse> errorMessageExtractor =
new HttpMessageConverterExtractor(ExceptionResponse.class, messageConverters);
ExceptionResponse errorObject = errorMessageExtractor.extractData(response);
throw new ResponseEntityErrorException(ResponseEntity.status(response.getRawStatusCode()).headers(response.getHeaders()).body(errorObject));
}

public void setMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
this.messageConverters = messageConverters;
}
}

RestTemplate 配置 - 您必须将 RestTemplate 的 errorHandler 设置为 ResponseEntityErrorHandler。

@Configuration
public class RestTemplateConfiguration {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntityErrorHandler errorHandler = new ResponseEntityErrorHandler();
errorHandler.setMessageConverters(restTemplate.getMessageConverters());
restTemplate.setErrorHandler(errorHandler);
return restTemplate;
}
}

调用方式

@Autowired restTemplate

String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
try {
ResponseEntity<Object> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, Object.class, uriParms);
int restCallStateCode = responseEntity.getStatusCodeValue();
} catch (ResponseEntityErrorException re) {
ResponseEntity<ErrorResponse> errorResponse = re.getErrorResponse();
}

关于java - 无法在 Spring 返回带有异常详细信息的 ResponseEntity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52183546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com