我如何为此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 ...
最佳答案
似乎您已导入javax.validation.ConstraintViolationException
而不是org.hibernate.exception.ConstraintViolationException
中的CustomResponseEntityExceptionHandler
。如果导入不正确,请导入org.hibernate.exception.ConstraintViolationException
。