gpt4 book ai didi

java - spring-boot 中的自定义 ConstraintViolationException

转载 作者:行者123 更新时间:2023-12-02 04:59:51 40 4
gpt4 key购买 nike

我如何捕获此 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 函数捕获。

谁能给我建议吗?

谢谢。
替代...

最佳答案

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

关于java - spring-boot 中的自定义 ConstraintViolationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56392155/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com