Absolutely! When handling exceptions like JpaSystemException (which may wrap low-level database exceptions such as constraint violations, deadlocks, or syntax errors), it's important to:
- Avoid exposing sensitive internal details (technical or stacktrace info).
- Provide an informative but generic message to the API consumer.
- Optionally, log the detailed message internally for debugging.
Below is the clean and idiomatic way to add a handler for JpaSystemException in your @ControllerAdvice-annotated ExceptionHandlerController.
✅ Example: Handling JpaSystemException in ExceptionHandlerController
import org.springframework.dao.DataAccessException;
import org.springframework.orm.jpa.JpaSystemException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// Define a standard error response DTO
class ErrorResponse {
private String message;
private int status;
public ErrorResponse(String message, int status) {
this.message = message;
this.status = status;
}
// Getters and setters
public String getMessage() { return message; }
public int getStatus() { return status; }
public void setMessage(String message) { this.message = message; }
public void setStatus(int status) { this.status = status; }
}
@ControllerAdvice
public class ExceptionHandlerController {
private static final Logger logger = LoggerFactory.getLogger(ExceptionHandlerController.class);
/**
* Handle any database-related exception wrapped in JpaSystemException.
*/
@ExceptionHandler(JpaSystemException.class)
public ResponseEntity<ErrorResponse> handleJpaSystemException(JpaSystemException ex) {
// Log the full stack trace for internal diagnostics
logger.error("Database operation failed", ex);
// Create a generic message for the API response
ErrorResponse response = new ErrorResponse(
"An unexpected error occurred while processing your request. Please contact support if the problem persists.",
HttpStatus.INTERNAL_SERVER_ERROR.value()
);
return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
}
// You can also optionally handle more specific exceptions like DataAccessException, etc.
}
✅ Why This Works Well
- API Safety: The response message is user-friendly and avoids exposing DB or ORM-specific details.
- Logging: Full details are
logged, enabling the dev/ops team to debug properly.
- Consistency: The
ErrorResponse makes the structure predictable for the client.
🧠 Optional Improvements
-
Global Error Response Structure:
Use a consistent structure for all errors (e.g., error codes, timestamps, trace ID).
{
"message": "An unexpected error occurred while processing your request. Please contact support if the problem persists.",
"status": 500,
"errorCode": "INTERNAL_DB_ERROR",
"timestamp": "2025-06-24T14:03:00Z"
}
-
Map More Exceptions:
If you're using JPA, consider also handling:
DataIntegrityViolationException
ConstraintViolationException
OptimisticLockingFailureException
🧪 Test Case Suggestion
For unit testing this handler:
@Test
void handleJpaSystemException_returnsInternalServerError() {
JpaSystemException ex = new JpaSystemException(new PersistenceException("Simulated DB error"));
ResponseEntity<ErrorResponse> response = controller.handleJpaSystemException(ex);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
assertEquals("An unexpected error occurred while processing your request. Please contact support if the problem persists.",
response.getBody().getMessage());
}
Let me know if you'd like to explore extending your exception handling with more metadata (like a global error code enumeration).