我已经创建了一个Spring Restful Service和Spring MVC应用程序。
宁静的服务:: 如果数据库中存在实体,则RESTful服务将返回其实体。如果不存在,它将在ResponseEntity对象中返回自定义Exception信息。
使用邮递员进行了预期的测试。
@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();
答案 0 :(得分:3)
这是预期的行为。当http状态为客户端错误或服务器错误时,REST模板将引发异常,而当HTTP状态不是错误状态时,REST模板将返回响应。
您必须提供实现以使用错误处理程序,将响应映射到响应实体并引发异常。
使用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();
}
答案 1 :(得分:1)
尝试在Exceptionhandler上使用@ResponseBody批注。例如:
public @ResponseBody ResponseEntity<ExceptionResponse> itemNotFEx(WebRequest webRequest, Exception exception) {... }
答案 2 :(得分:0)
我已经启动了您的应用程序,并且运行正常。
Maven:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
控制器类为:
@Controller
public class ValidationController {
@GetMapping(value = "/validate/{itemId}")
public @ResponseBody ResponseEntity<MyItem> validateItem(@PathVariable Long itemId) {
if (itemId.equals(Long.valueOf(1))) {
throw new ItemNotFoundException();
}
return new ResponseEntity<>(new MyItem(), HttpStatus.OK);
}
@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, HttpStatus.NOT_FOUND);
return responseEntity;
}
}
和测试:
@RunWith(SpringRunner.class)
@WebMvcTest(value = ValidationController.class, secure = false)
public class TestValidationController {
@Autowired
private MockMvc mockMvc;
@Test
public void testExpectNotFound() throws Exception {
mockMvc.perform(get("/validate/1"))
.andExpect(status().isNotFound());
}
@Test
public void testExpectFound() throws Exception {
mockMvc.perform(get("/validate/2"))
.andExpect(status().isOk());
}
}
您确定要与RestTemplate一起使用的网址正确吗?
String url = "http://localhost:8080/ItemServices/items/validate/{itemId}";
您的get方法是@GetMapping(value =“ / validate / {itemId}”
如果您没有控制器级别的请求映射,则网址应为:
http://localhost:8080/validate/1
另一个区别是控制器方法上缺少@ResponseBody。
答案 3 :(得分:0)
您应该使用自定义异常处理程序来解决您的问题。看起来像这样
ProductRequest productRequest = new ProductRequest();
ArrayList<Product> productList = new ArrayList<>();
Product product = new Product(1, "Samsung Galaxy A5", 234.54);
productList.add(product);
productRequest.products = productList;
Call<ProductResponse> productResponseCall = jsonPostService.addProducts(productRequest);
productResponseCall.enqueue(new Callback<ProductResponse>() {
@Override
public void onResponse(Call<ProductResponse> call, Response<ProductResponse> response) {
ProductResponse productResponse = response.body(); // this your result
}
@Override
public void onFailure(Call<ProductResponse> call, Throwable t) {
Log.e("response-failure", call.toString());
}
});
您的代码应引发一些异常,例如:
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public CustomResponseEntityExceptionHandler() {
super();
}
// 404
@ExceptionHandler(value = { EntityNotFoundException.class, ResourceNotFoundException.class })
protected ResponseEntity<Object> handleNotFound(final RuntimeException ex, final WebRequest request) {
BaseResponse responseError = new BaseResponse(HttpStatus.NOT_FOUND.value(),HttpStatus.NOT_FOUND.name(),
Constants.HttpStatusMsg.ERROR_NOT_FOUND);
logger.error(ex.getMessage());
return handleExceptionInternal(ex, responseError, new HttpHeaders(), HttpStatus.NOT_FOUND, request);
}
}
如果再次在其他地方遇到这种情况,则只会引发上述异常。您的经理将照顾其余的东西。
希望获得帮助。