如何在处理ResourceNotFoundException时使用@ResponseStatus批注

问题描述 投票:0回答:1

我有以下服务类:

@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中。

问题:如何利用ResponseStatusResourceNotFoundException注释而不是添加重复的代码?

java spring spring-mvc spring-data-rest
1个回答
0
投票

删除handleResourceNotFound并让框架为您处理,或从Response方法返回适当的handleResourceNotFound

通过声明这样的处理程序,你说你将处理这种情况,因此框架正在退出。

© www.soinside.com 2019 - 2024. All rights reserved.