繁体   English   中英

在 Spring Boot 中实现自定义异常

[英]Implementing custom exceptions in Spring Boot

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

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

ErrorDetails.java
GlobalExceptionHandler.java
ResourceNotFoundException.java

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

每当出现资源不可用的情况时,就会抛出 ResourceNotFoundException 即throw new ResourceNotFoundException("Error message of your choice");

例如,在方法getCustomerTypebyID中的 class CustomerTypeRepository中,而不是下面的代码:

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 处理程序实现了。 所以不用担心。

我相信将检查异常声明为合同,所以我会做这样的事情

@Service
public class CustomerCategorizationService {

@Autowired
private CustomerTypeRepository customerTypeRepository;

  // -------------- CustomerType API ----------------------- ///

  public CustomerType saveCustomerType(CustomerType obj) throws ServiceException {

其中ServiceException是应用程序中定义的自定义检查异常。

public CustomerType saveCustomerType(CustomerType obj) throws ServiceException {
  //Other code
  Long id;
  try {
    id = customerTypeRepository.save(obj);
  }catch(DataAccessException cause) {
    throw new ServiceException(cause.getMessage());
  }
  return id;
}

@ControllerAdvice

@ExceptionHandler(ServiceException.class)
public ResponseEntity<?> resourceNotFoundException(ServiceException ex, WebRequest request) {
    ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), 
 request.getDescription(false));
    return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}

我们可以进一步 go 并从 Controller class (比如ResourceException )抛出自定义异常,它将包装ServiceException 在这种情况下,我的@ControllerAdvice只需要处理ResourceException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM