0

I am making a Spring Boot app with MySQL database attached to it.

I have already marked username as unique in the user-table, and the DB throws a MySQLIntegrityConstraintViolationException when i try to add a new user with an existing username.

Is there a way to make the ControllerAdvice handle this exception ? I tried making the handler like this :

@ExceptionHandler(MySQLIntegrityConstraintViolationException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    @ResponseBody
    public MyBadInputResponse databaseIntegrityViolationDuplicate(MySQLIntegrityConstraintViolationException ex) {
        MyBadInputResponse bir = new MyBadInputResponse("The request value already exists in the database", 
                ex.getLocalizedMessage());
        logger.error(bir.toString());
        return bir;
    }

But it doesn't work.

Shadow
  • 33,525
  • 10
  • 51
  • 64
Lazaruss
  • 1,107
  • 1
  • 13
  • 24
  • Are you annotating your bean (that contains the `ExceptionHandler` method) with a `@ControllerAdvice` ? – Abdelghani Roussi Oct 27 '19 at 16:49
  • Of course. And all the other ExceptionHandlers in that controller advice are working. – Lazaruss Oct 27 '19 at 18:06
  • Generally those specific exceptions are converted to Spring `DataAccessException` subclasses. So your code will never throw a `MySQLIntegrityConstraintViolationException` but rather a `DataIntegrityViolationException` from Spring. – M. Deinum Oct 28 '19 at 10:02
  • That seems to work. Thanks. :) – Lazaruss Oct 30 '19 at 18:56

0 Answers0