【问题标题】:Spring JPA-Repository with bean validation: Poor error response带有 bean 验证的 Spring JPA-Repository:错误响应差
【发布时间】:2018-10-05 15:08:15
【问题描述】:

我正在使用这样的模型对象:

@Entity
public class Address {

    @Id
    @GeneratedValue
    private long id;

    @NotNull
    @Size(min = 1, max = 20)
    private String location;

    @OneToOne(mappedBy = "address")
    private Person person;
}

有一个仓库

@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends PagingAndSortingRepository<Address, Long> {

}

当我尝试发布一个违反 bean 约束的对象时,我得到一个糟糕的错误响应:

{"timestamp":"2018-10-05T14:48:23.667+0000","status":500,"error":"内部 服务器错误","message":"无法提交 JPA 事务;嵌套的 异常是 javax.persistence.RollbackException: Error while 提交事务","path":"/address"}

如果我不自己实现每个 REST 控制器,如何获得有用的错误消息?

【问题讨论】:

标签: java spring spring-data-jpa spring-data spring-rest


【解决方案1】:

定义控制器建议以全局处理异常并将您的自定义消息作为字符串或ErrorResponse 对象返回(您可以在其中定义自己的属性)。

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RollbackException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public String handleRollbackException(RollbackException ex) {

        String errorMessage = "Your custom message";
        return errorMessage ;
    }

}

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 2017-05-19
    • 2022-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2016-09-12
    • 1970-01-01
    • 2019-01-29
    相关资源
    最近更新 更多