简体   繁体   中英

Implementing custom exceptions in Spring Boot

I have a simple spring boot application in which I have alot of tables. I have build their models, repositories, service and controller files. I have also tested all the apis through postman. Now I need to implement custom exception in my models. Since I am at the beginning stage and learning things, I am a little confused as to how can I apply exceptions?

From what I have explored, I need to create three files

ErrorDetails.java
GlobalExceptionHandler.java
ResourceNotFoundException.java

Is this correct? If yes suppose I have added these files in my project. How do I implement these exceptions in my apis? Can anybody help me? Would mean alot. Thanks!

Whenever there is a case where resources will be not available then throw ResourceNotFoundException ie throw new ResourceNotFoundException("Error message of your choice");

For example in class CustomerTypeRepository within method getCustomerTypebyID instead of below code:

if (a == null) {
  return ResponseEntity.notFound().build();
}

you can write

if (a == null) {
  throw new ResourceNotFoundException("Customer type doesn't exist with the given id: "+Id);
}

and after that @ControllerAdvice GlobalExceptionHandler has already implamented for ResourceNotFoundException handler. So no need to worry about.

I believe in declaring checked exception as a contract, so I would do something like this

@Service
public class CustomerCategorizationService {

@Autowired
private CustomerTypeRepository customerTypeRepository;

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

  public CustomerType saveCustomerType(CustomerType obj) throws ServiceException {

Where ServiceException is custom checked exception defined in application.

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;
}

And in @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);
}

We can go one step further and throw custom exception from Controller class (say ResourceException ) which will wrap ServiceException . In that case my @ControllerAdvice needs to only deal with ResourceException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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