春季启动中的自定义ConstraintViolationException

时间:2019-05-31 09:18:08

标签: java spring-boot exception

如何为此ConstraintViolationException捕获异常:

{
    "timestamp": "2019-05-31T07:23:03.419+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "could not execute statement; SQL [n/a]; constraint [fkitcllv8yn2id9lj3rmw3wskhd]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
    "path": "/pelajar"
}

当我尝试删除记录时,会发生此说明。但是该记录仍被其他表中的其他记录用作参考。

我有2个CustomExceptionHandle:  捕获一般异常的第一  第二个用于捕获ConstraintViolation异常。

但是在我的程序中,每次ConstraintViolation触发时,都会执行handleAllExceptions。 我的期望是应该执行handleConstraint函数。

@ControllerAdvice
@RestController
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public  ResponseEntity<Object> handleConstraint(ConstraintViolationException ex, 
            WebRequest request ) {

        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), "Record still have reference from other table",
                request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);       
    }


    @Order(Ordered.LOWEST_PRECEDENCE)
    @ExceptionHandler(value = {Exception.class})
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage()+" Custom Error",
                request.getDescription(false));
        return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

但是,如果删除handleAllExceptions,则ConstraintViolationException将由handleConstraint函数捕获。

有人可以给我建议吗?

谢谢。
Alt ...

1 个答案:

答案 0 :(得分:0)

似乎您已导入javax.validation.ConstraintViolationException而不是org.hibernate.exception.ConstraintViolationException中的CustomResponseEntityExceptionHandler。如果导入不正确,请导入org.hibernate.exception.ConstraintViolationException