我有一个自定义建议来处理从REST API 错误处理复制的控制器的异常以及处理 DataIntegrityViolationException 的方法:
@ExceptionHandler(DataIntegrityViolationException.class)
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex,
WebRequest request) {
if (ex.getCause() instanceof ConstraintViolationException) {
return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex));
}
return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
}
ApiError - 构造函数
public ApiError(HttpStatus status, String message, Throwable ex) {
this();
this.status = status;
this.message = message;
this.debugMessage = ex.getLocalizedMessage();
}
发生错误时,响应会显示如下消息:
"apierror": {
"status": "CONFLICT",
"message": "Database error",
"debugMessage": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"constraintName": null
}
问题是消息没有向消费者显示真正的问题,因为真正的问题在 ( ex.getCause().getCause().getMessage()
) 内部:
Cannot delete or update a parent row: a foreign key constraint fails
(`cup_orchestrator`.`cpo_production_cycle`, CONSTRAINT `fk_cpo_production_cycle_cpo_cycle_type1`
FOREIGN KEY (`cycle_type_id`) REFERENCES `cpo_cycle_type` (`cycle_type_id`))
我想处理这样的消息:“记录仍然有来自其他表的引用”;
是否有任何自定义处理程序异常可以以更具体的方式处理 sql 异常?