首页 > 解决方案 > 在 Spring Boot 中实现自定义异常

问题描述

我有一个简单的 Spring Boot 应用程序,其中有很多表。我已经构建了他们的模型、存储库、服务和控制器文件。我还通过邮递员测试了所有的api。现在我需要在我的模型中实现自定义异常。由于我处于起步阶段并且正在学习东西,所以我对如何应用例外感到有些困惑?

根据我的探索,我需要创建三个文件

ErrorDetails.java
GlobalExceptionHandler.java
ResourceNotFoundException.java

这个对吗?如果是的话,假设我已经在我的项目中添加了这些文件。如何在我的 API 中实现这些异常?有谁能够帮我?意味着很多。谢谢!

标签: javaspring-bootexception

解决方案


每当出现资源不可用的情况时,抛出 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 处理程序实现了。所以不用担心。


推荐阅读