リソースが見つからない場合に 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 でいくつかのことを行うことができると考えていました。ただし、例外は起動で、アプリがダウンします。
例外を送信せずに、ResponseEntity に入力するための restTemplate の特定の構成はありますか。