How do I catch the constraint violation exception from EclipseLink?

后端 未结 6 2387
-上瘾入骨i
-上瘾入骨i 2021-02-19 06:54

I am using EclipseLink in my web application, and I am having a hard time gracefully catching and handling Exceptions it generates. I see from this thread what seems to be a si

6条回答
  •  我寻月下人不归
    2021-02-19 07:08

    I'm using Spring Boot 1.1.9 + EclipseLink 2.5.2. This is the only way I can catch ConstraintViolationException. Note that my handleError(ConstraintViolationException) is a very simple implementation which just returns the first violation it finds.

    Note that this code was also required when I switched to Hibernate 4.3.7 and Hibernate Validator 5.1.3.

    It seems that adding PersistenceExceptionTranslationPostProcessor exceptionTranslation() to my persistence JavaConfig class also has no effect.


    import javax.persistence.RollbackException;
    import javax.validation.ConstraintViolation;
    import javax.validation.ConstraintViolationException;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.transaction.TransactionSystemException;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    @ControllerAdvice
    class GlobalExceptionHandler
    {
        @ExceptionHandler(TransactionSystemException.class)
        public ResponseEntity handleError(final TransactionSystemException tse)
        {
            if(tse.getCause() != null && tse.getCause() instanceof RollbackException)
            {
                final RollbackException re = (RollbackException) tse.getCause();
    
                if(re.getCause() != null && re.getCause() instanceof ConstraintViolationException)
                {
                    return handleError((ConstraintViolationException) re.getCause());
                }
            }
    
            throw tse;
        }
    
    
        @ExceptionHandler(ConstraintViolationException.class)
        @SuppressWarnings("unused")
        public ResponseEntity handleError(final ConstraintViolationException cve)
        {
            for(final ConstraintViolation v : cve.getConstraintViolations())
            {
                return new ResponseEntity(new Object()
                {
                    public String getErrorCode()
                    {
                        return "VALIDATION_ERROR";
                    }
    
    
                    public String getMessage()
                    {
                        return v.getMessage();
                    }
                }, HttpStatus.BAD_REQUEST);
            }
    
            throw cve;
        }
    }
    
        

    提交回复
    热议问题