在JPA/Hibernate中添加自定义错误消息的更好方法是:

huangapple go评论82阅读模式
英文:

Better way to add custom error message during Unique Constrains JPA/Hibernate

问题

我认为在Spring Boot/Hibernate中有更好的方法来做这件事。有很多表格,我不想为每个表格都添加用户定义的模型。

我有一个实体:

@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;
}

如何在我的REST API中发送自定义消息,指示代码重复或名称重复?

英文:

I think there is a better way to do this in Spring boot/hibernate. There are many tables and I don't want to add User Defined model for every table: here

I have an entity

@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;
}

How do I send a custom message for my REST APIs stating if code is duplicate or name is duplicate?

答案1

得分: 2

在最外层捕获异常如下:

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层检查以显示错误消息的地方。

英文:

In the outermost layer, catch the exception as follows:

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

Create a custom exception for each unique key like this:

public class DuplicatedNameException extends Exception {

	public DuplicatedNameException(String message){
    	super(message);
    }

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

Define an exception handler that extends from the ResponseEntityExceptionHandler class and treats the received exception as follows:

@ExceptionHandler({ DuplicatedNameException.class })
    public ResponseEntity&lt;Object&gt; handleDuplicatedNameException(Exception anException, WebRequest request) {

    [...]

	return new ResponseEntity&lt;&gt;(anException, new HttpHeaders(), YOUR_HTTP_STATUS_WITH_CUSTOM_CODE_HERE);
}

This HTTPStatus is the one that you should check in the web layer to show the error message

huangapple
  • 本文由 发表于 2020年8月11日 13:26:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/63352008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定