In a Spring Boot application, custom exceptions can be created and handled using Java’s standard exception handling mechanisms, along with Spring’s exception handling features.
To create a custom exception, you can create a new class that extends Exception or one of its subclasses, such as RuntimeException. Here is an example of a custom exception:
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
In this example, we have created a custom exception called UserNotFoundException, which extends RuntimeException. This exception can be thrown when a user is not found in the database.
To handle the custom exception, we can create an exception handler method in a @ControllerAdvice class. Here is an example:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFoundException(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT\_FOUND).body(ex.getMessage());
}
}
In this example, we have created an exception handler method called handleUserNotFoundException that handles UserNotFoundException. The method returns a ResponseEntity object with a status code of 404 NOT_FOUND and the exception message as the response body.
To throw the custom exception, we can simply create a new instance of the exception and throw it in the appropriate place in our code. Here is an example:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
Optional<User> user = userRepository.findById(id);
if (user.isPresent()) {
return user.get();
} else {
throw new UserNotFoundException("User not found with ID: " + id);
}
}
}
In this example, we have a UserService class that retrieves a user by ID from a UserRepository. If the user is not found, we throw a UserNotFoundException with an appropriate error message.
Overall, creating and handling custom exceptions in a Spring Boot application is a powerful and flexible way to handle error conditions in your code. By creating custom exceptions and handling them with @ControllerAdvice and @ExceptionHandler, developers can provide meaningful error messages to users and gracefully handle exceptions in their code.