[英]How exactly works the @ResponseStatus Spring annotation for RESTful application?
[英]How to utilize the @ResponseStatus annotation when handling the ResourceNotFoundException
我有以下服務類:
@Service
public class CitiesServiceImpl implements CitiesService {
@Autowired
private CitiesRepository citiesRepository;
@Override
public City getCityById(Integer cityId) {
return citiesRepository.findById(cityId)
.orElseThrow(ResourceNotFoundException::new);
}
}
它在我的控制器中使用:
@RestController
@RequestMapping("/cities")
public class CitiesController {
@Autowired
private CitiesService citiesService;
@GetMapping("/{cityId}")
public City readCity(@PathVariable Integer cityId) {
return citiesService.getCityById(cityId);
}
@ExceptionHandler(ResourceNotFoundException.class)
String handleResourceNotFound(Exception e) {
return e.getMessage();
}
}
因此,當readCity
是帶一個不存在的cityID
,該ResourceNotFoundException
將被拋出,然后由處理handleResourceNotFound
異常處理程序。
但是, 當處理ResouceNotFoundException
時,響應中的狀態代碼仍為202,即OK。 似乎在運行時沒有使用ResourceNotFoundException
中的@ResponseStatus
注釋。 這可以通過將@ResponseStatus(value = HttpStatus.NOT_FOUND)添加到方法handleResourceNotFound
來修復,但是這樣的代碼是重復的,因為@ResponseStatus
注釋已經在ResourceNotFoundException
。
問題:如何利用ResourceNotFoundException
的ResponseStatus
注釋而不是添加重復的代碼?
刪除handleResourceNotFound
並讓框架為您處理,或從handleResourceNotFound
方法返回正確的Response
。
通過聲明這樣的處理程序,你說你將處理這種情況,因此框架正在退出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.