首页 > 解决方案 > 处理 ResourceNotFoundException 时如何利用 @ResponseStatus 注释

问题描述

我有以下服务等级:

@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使用不存在的 调用 时cityIDResourceNotFoundException将抛出 ,然后由handleResourceNotFound异常处理程序处理。

但是,处理ResouceNotFoundException完之后,响应中的状态码还是202,即OK。似乎在运行时没有使用@ResponseStatus注释。ResourceNotFoundException这可以通过将 @ResponseStatus(value=HttpStatus.NOT_FOUND) 添加到方法来解决handleResourceNotFound,但是这样的代码是重复的,因为@ResponseStatus注释已经在ResourceNotFoundException.

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

标签: javaspringspring-mvcspring-data-rest

解决方案


删除它handleResourceNotFound并让框架为您处理它,或者ResponsehandleResourceNotFound方法中正确返回。

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


推荐阅读