我有以下服务类:
@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。似乎@ResponseStatus
中的ResourceNotFoundException
注释未在运行时使用。这可以通过将@ResponseStatus(value = HttpStatus.NOT_FOUND)添加到方法handleResourceNotFound
来修复,但是这样的代码是重复的,因为@ResponseStatus
注释已经在ResourceNotFoundException
中。
问题:如何利用ResponseStatus
的ResourceNotFoundException
注释而不是添加重复的代码?
删除handleResourceNotFound
并让框架为您处理,或从Response
方法返回适当的handleResourceNotFound
。
通过声明这样的处理程序,你说你将处理这种情况,因此框架正在退出。