在Unique Constraints JPA/Hibernate期间添加自定义错误消息的更好方法



我认为在Spring引导/休眠中有更好的方法可以做到这一点。有很多表,我不想为每个表添加用户定义模型:这里是

我有一个实体

@Entity
public class Item extends ExtraEntity {
@NotEmpty(message = "Item code can not be Empty !")
@Column(unique = true)
private String code;
@NotEmpty (message = "Item name can not be Empty !")
@Column(unique = true)
private String name;
}

如何为RESTAPI发送自定义消息,说明代码是否重复或名称是否重复?

在最外层,捕获异常,如下所示:

try {
newEntity = ourService.createUpdate(entity);
} catch (JpaSystemException jpae) {
if (jpae.getCause().getCause() instanceof ConstraintViolationException) {
if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_CODE_01")){
throw new DuplicatedCodeException("Message",jpae);
} else if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_NAME_01")){
throw new DuplicatedNameException("Message",jpae);
}
}
}

为每个唯一密钥创建一个自定义异常,如下所示:

public class DuplicatedNameException extends Exception {
public DuplicatedNameException(String message){
super(message);
}
public DuplicatedNameException(String message, Throwable anException){
super(message, anException);
}
}

定义一个从ResponseEntityExceptionHandler类扩展而来的异常处理程序,并按如下方式处理接收到的异常:

@ExceptionHandler({ DuplicatedNameException.class })
public ResponseEntity<Object> handleDuplicatedNameException(Exception anException, WebRequest request) {
[...]
return new ResponseEntity<>(anException, new HttpHeaders(), YOUR_HTTP_STATUS_WITH_CUSTOM_CODE_HERE);
}

此HTTPStatus是您应该在web层中检查以显示错误消息的状态

最新更新