java - 处理 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
使用不存在的 调用 时cityID
,ResourceNotFoundException
将抛出 ,然后由handleResourceNotFound
异常处理程序处理。
但是,处理ResouceNotFoundException
完之后,响应中的状态码还是202,即OK。似乎在运行时没有使用@ResponseStatus
注释。ResourceNotFoundException
这可以通过将 @ResponseStatus(value=HttpStatus.NOT_FOUND) 添加到方法来解决handleResourceNotFound
,但是这样的代码是重复的,因为@ResponseStatus
注释已经在ResourceNotFoundException
.
问题:如何利用ResponseStatus
注释ResourceNotFoundException
而不是添加重复代码?
解决方案
删除它handleResourceNotFound
并让框架为您处理它,或者Response
从handleResourceNotFound
方法中正确返回。
通过声明这样的处理程序,您是在说您将处理这种情况,因此框架正在退出。
推荐阅读
- python - 将 Django-form 发送到其他服务器进行数据处理
- mysql - 如何在单个 docker 容器中运行项目并在 docker 文件系统中运行已安装的项目依赖项,而不是使用 docker 镜像?
- spring - 如何在 SpringBoot 中拥有同一个类的两个实现(测试和实际)?
- java - Room DB - DISTINCT 用于组合 2 个字段 (GPS)
- python - 模块“cv2.cv2”没有属性“sfm”
- c# - 控制台应用程序中的 C# 多个入口点
- python - 在 Cython 中使用数组时计算速度的巨大损失
- c# - Blazor 项目中的 C++ DLL
- gradle - Gradle:让依赖的版本依赖于传递依赖的版本
- ios - 正则表达式以@开头,以空格结尾