PersistenceExceptionHandler implements BaseExceptionHandler<PersistenceException> { @Override @ResponseBody @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = {PersistenceException.class}) public MessageResource handle(final PersistenceException e) { LOGGER.error("Handling persistence exception", e); MessageResource message = new MessageResource(); message.setMessageType(MessageType.ERROR); if (e.getCause() instanceof ConstraintViolationException) { message.setMessage(MessageFormat.format("ConstraintViolationName : {0}", ((ConstraintViolationException) e.getCause()).getConstraintName())); } else { message.setMessage(e.getMessage()); } return message; }  @Override @ResponseBody @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = {PersistenceException.class}) MessageResource handle(final PersistenceException e);  }
@Test public void shouldChangeExceptionMessage() throws Exception { ConstraintViolationException constraintViolationException = new ConstraintViolationException("Could not execute JDBC batch update", Mockito.mock(SQLException.class), "ConstraintName"); PersistenceException exception = new PersistenceException("", constraintViolationException); MessageResource expected = new MessageResource(); expected.setMessageType(MessageType.ERROR); expected.setMessage(MessageFormat.format("ConstraintViolationName : {0}", constraintViolationException.getConstraintName())); MessageResource actual = handler.handle(exception); assertEquals(expected, actual); }
@Test public void shouldNotChangeExceptionMessage() throws Exception { NoResultException noResultException = new NoResultException(""); PersistenceException exception = new PersistenceException("Without result", noResultException); MessageResource expected = new MessageResource(); expected.setMessageType(MessageType.ERROR); expected.setMessage(exception.getMessage()); MessageResource actual = handler.handle(exception); assertEquals(expected, actual); }