我有一个休息服务,当找不到资源时会发送 404 错误。这里是我的控制器的来源和发送 Http 404 的异常。
@Controller
@RequestMapping("/site")
public class SiteController
{
@Autowired
private IStoreManager storeManager;
@RequestMapping(value = "/stores/{pkStore}", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public StoreDto getStoreByPk(@PathVariable long pkStore) {
Store s = storeManager.getStore(pkStore);
if (null == s) {
throw new ResourceNotFoundException("no store with pkStore : " + pkStore);
}
return StoreDto.entityToDto(s);
}
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException
{
private static final long serialVersionUID = -6252766749487342137L;
public ResourceNotFoundException(String message) {
super(message);
}
}
当我尝试使用以下代码使用 RestTemplate 调用它时:
ResponseEntity<StoreDto> r = restTemplate.getForEntity(url, StoreDto.class, m);
System.out.println(r.getStatusCode());
System.out.println(r.getBody());
我收到此异常:
org.springframework.web.client.RestTemplate handleResponseError
ATTENTION: GET request for "http://........./stores/99" resulted in 404 (Introuvable); invoking error handler
org.springframework.web.client.HttpClientErrorException: 404 Introuvable
我在想我可以探索我的 responseEntity 对象并使用 statusCode 做一些事情。但例外是启动,我的应用程序出现故障。
restTemplate 是否有特定配置不发送异常但填充我的 ResponseEntity。