java - 在 Spring Boot 中实现自定义异常
问题描述
我有一个简单的 Spring Boot 应用程序,其中有很多表。我已经构建了他们的模型、存储库、服务和控制器文件。我还通过邮递员测试了所有的api。现在我需要在我的模型中实现自定义异常。由于我处于起步阶段并且正在学习东西,所以我对如何应用例外感到有些困惑?
根据我的探索,我需要创建三个文件
ErrorDetails.java
GlobalExceptionHandler.java
ResourceNotFoundException.java
这个对吗?如果是的话,假设我已经在我的项目中添加了这些文件。如何在我的 API 中实现这些异常?有谁能够帮我?意味着很多。谢谢!
解决方案
每当出现资源不可用的情况时,抛出 ResourceNotFoundException 即throw new ResourceNotFoundException("Error message of your choice");
例如在CustomerTypeRepository
方法内的类中,getCustomerTypebyID
而不是下面的代码:
if (a == null) {
return ResponseEntity.notFound().build();
}
你可以写
if (a == null) {
throw new ResourceNotFoundException("Customer type doesn't exist with the given id: "+Id);
}
之后@ControllerAdvice GlobalExceptionHandler
已经为 ResourceNotFoundException 处理程序实现了。所以不用担心。
推荐阅读
- ruby-on-rails - 在 Rails 5.2 中使用 Has_Many_Through 记录保存记录
- python - 将 df1 头插入另一个 df2
- google-drive-android-api - 拒绝访问从谷歌驱动器 api 下载文件
- ios - 如何在单个 3rd 方框架中打包多个内部 swift 模块(框架)?
- elasticsearch - Elasticsearch 错误:cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark 超出
- asp.net-web-api - 问题通过 html5 FormData 将 multipart/form-data 发布到 c# Api
- c++ - Qt 创建者包括守卫模式
- java - 硒驱动程序选择错误
- dc.js - dc.js 为气泡图分组从错误的组中删除
- java - 如何使用fabric8 docker-maven-plugin从Dockerfile构建docker镜像?