Exception handling in java
- Get link
- X
- Other Apps
!! While adding data in database, types of exception can occurs !!
@PostMapping("/add")
public Employee addEmployee(@RequestBody Employee employee) {
return employeeService.saveEmployee(employee);
}
When adding data to a database in a Spring Boot application, several types of exceptions can be thrown. These exceptions may arise from various layers, including Spring Data, JPA, or the underlying JDBC driver. Below is a categorization of potential exceptions:
1. Data Access Exceptions (Spring Framework)
Spring wraps exceptions from the persistence framework or database in subclasses of DataAccessException. Common exceptions include:
DataIntegrityViolationException
- Occurs when constraints (e.g., unique, foreign key, not null) are violated.
DuplicateKeyException
- Thrown for unique constraint violations or duplicate entries.
EmptyResultDataAccessException
- Happens if a query expecting a result (e.g., findById) returns no data.
IncorrectResultSizeDataAccessException
- Thrown when a query returns an unexpected number of rows.
DataRetrievalFailureException
- Issues with fetching data (e.g., missing row in a join).
QueryTimeoutException
- Database operation times out.
2. JPA Exceptions (Hibernate or Other Providers)
If you are using JPA with Hibernate or another provider, the following exceptions may occur:
EntityExistsException
- Trying to persist an entity with the same primary key as an existing entity.
EntityNotFoundException
- When an entity reference is resolved but no actual entity exists in the database.
TransactionRequiredException
- Attempting an operation outside a transaction context when one is required.
OptimisticLockException
- Version conflict during an update with optimistic locking.
PersistenceException
- General JPA persistence errors.
ConstraintViolationException (Hibernate-specific)
- Violation of database constraints.
3. JDBC Exceptions
Underlying JDBC exceptions may bubble up if not handled by Spring or JPA:
SQLSyntaxErrorException
- Issues with SQL syntax, such as malformed queries.
SQLIntegrityConstraintViolationException
- Constraint violations at the database level.
SQLTimeoutException
- Timeout during a database operation.
SQLException
- General SQL-related issues.
4. Custom Application Exceptions
You may define your own custom exceptions for business logic errors, such as:
InvalidDataException
- Thrown when input validation fails before reaching the database.
EntityAlreadyExistsException
- Indicates that the entity already exists in your application's domain logic.
DatabaseConnectionException
- Custom handling for connection issues.
5. Transactional Exceptions
When dealing with transactions, exceptions can occur, such as:
RollbackException
- Thrown if a transaction fails or is explicitly rolled back.
HeuristicRollbackException
- Partial rollback in a distributed transaction.
6. Others
IllegalArgumentException
- Incorrect arguments passed to repository methods.
ConversionFailedException
- Issues with type conversion during query operations.
Best Practices for Handling Exceptions
- Global Exception Handling: Use
@ControllerAdviceand@ExceptionHandlerto manage exceptions globally. - Transaction Management: Ensure proper transaction boundaries using
@Transactional. - Validation: Validate data using
@Validor@Validatedto avoid sending invalid data to the database. - Logging: Log exceptions for debugging and monitoring.
- Database-Specific Codes: Be mindful of database-specific exceptions or error codes (e.g., SQLState).
| Scenario | Cause | Recommended Handling |
|---|---|---|
| ๐ Validation Failure | Missing or invalid fields in request | Return 400 Bad Request |
| ๐ Constraint Violation | Duplicate key, foreign key error | Return 409 Conflict or 400 Bad Request |
| ๐ Database Connectivity Issues | DB is down, timeout, etc. | Return 503 Service Unavailable |
| ๐งจ Unexpected Exception | Null pointer, mapping error, etc. | Return 500 Internal Server Error |
| ❌ Business Rule Violation | E.g., “cannot pay more than balance” | Return 400 Bad Request with custom error messageHow to Handle These GracefullyStep 1: ❗ Validate Input with
|
- Get link
- X
- Other Apps
Comments
Post a Comment