How I catch exception for this 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"
}
This Excaption is happen, when I try to deleting a record. But that record still used as reference by other record in other table.
I Have 2 CustomExceptionHandle : the 1st for catch general exception and the 2nd for catch ConstraintViolation exception.
But in my program, each time ConstraintViolation trigger-up, the handleAllExceptions will be executed. My expectation is handleConstraint function should be executed.
@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);
}
}
But, If I remove handleAllExceptions the ConstraintViolationException will be catch by handleConstraint function.
Can anyone give me advice ?
Thank You.
Alt...
Seems you have imported javax.validation.ConstraintViolationException
instead of org.hibernate.exception.ConstraintViolationException
in CustomResponseEntityExceptionHandler
. Kindly import org.hibernate.exception.ConstraintViolationException
if not imported correctly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.