Spring boot 如何改进使用@RepositoryRestResource时的错误响应

Spring boot 如何改进使用@RepositoryRestResource时的错误响应,spring-boot,spring-data-jpa,spring-data-rest,Spring Boot,Spring Data Jpa,Spring Data Rest,我在分页和排序存储库中使用spring的@RepositoryRestResource注释 当我向相应的端点发送错误的负载时,返回的错误响应很难解析,例如 { "cause": { "cause": { "cause": null, "message": "ERROR: duplicate key value violates unique constraint \"uk_bawli8xm92f30ei6x9p3h8eju\"\n Detail: Key (

我在
分页和排序存储库中使用spring的
@RepositoryRestResource
注释

当我向相应的端点发送错误的负载时,返回的错误响应很难解析,例如

{
  "cause": {
    "cause": {
      "cause": null,
      "message": "ERROR: duplicate key value violates unique constraint \"uk_bawli8xm92f30ei6x9p3h8eju\"\n  Detail: Key (email)=(jhunstone0@netlog.com) already exists."
    },
    "message": "could not execute statement"
  },
  "message": "could not execute statement; SQL [n/a]; constraint [uk_bawli8xm92f30ei6x9p3h8eju]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"
}

是否有任何方法来配置消息,以便明确哪个字段(此处:电子邮件)导致了错误?

关于错误处理-您可以为此类异常实施一个约束,从根本原因中提取约束名称,分析它并为用户创建相应的消息

一些错误处理示例:

已更新

您应该检查应用程序日志以确定必须处理的异常。如果我没有被误认为违反了约束,我们必须处理
org.springframework.dao.DataIntegrityViolationException
,例如:

@ControllerAdvice
公共类CommonExceptionHandler扩展了ResponseEntityExceptionHandler{
@ExceptionHandler(DataIntegrityViolationException.class)
ResponseEntity handleDataIntegrityViolation(DataIntegrityViolationException ex,HttpServletRequest请求){
String causeMessage=NestedExceptionUtils.GetMostSpecificCase(ex).getMessage();//确定消息的根本原因
String reqPath=req.getServletPath();//获取请求路径
String userMessage=…//决定要向用户显示的消息
HttpStatus status=HttpStatus…//决定响应的状态,例如HttpStatus.CONFLICT
ApiErrorMessage=新建ApiErrorMessage(userMessage,status,reqPath);//创建自定义错误消息
返回新的响应属性(消息、状态);//将响应返回给用户
}
//其他处理程序
}

或者,您可以像在官方中那样更容易地实现此处理程序。

您能告诉我,在这些示例中,导致错误的确切字段是在哪里确定的吗?我在博客文章的书面文本中看到了它,但在给定的代码中找不到它。@cbo在第一个示例的第一个示例中。我更新了答案。。。