spring-boot - 使用 @RepositoryRestResource 时如何改进错误响应

标签 spring-boot spring-data-jpa spring-data-rest

我在 PagingAndSortingRepository 上使用 spring 的 @RepositoryRestResource 注释。

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

{
  "cause": {
    "cause": {
      "cause": null,
      "message": "ERROR: duplicate key value violates unique constraint \"uk_bawli8xm92f30ei6x9p3h8eju\"\n  Detail: Key (email)=(<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd5d7cad1cccbd0d1da8fffd1dacbd3d0d891dcd0d2" rel="noreferrer noopener nofollow">[email protected]</a>) 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"
}

有什么方法可以配置消息,以便清楚哪个字段(此处:电子邮件)导致错误?

最佳答案

关于错误处理 - 您可以实现 custom exception handler对于此类异常,从根本原因中提取约束名称,进行分析并为用户创建相应的消息。

一些错误处理示例:1 , 2 .

已更新

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

@ControllerAdvice
public class CommonExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(DataIntegrityViolationException.class)
  ResponseEntity<?> handleDataIntegrityViolation(DataIntegrityViolationException ex, HttpServletRequest req) {

        String causeMessage = NestedExceptionUtils.getMostSpecificCause(ex).getMessage(); // determine the root cause message

        String reqPath = req.getServletPath(); // get the request path            

        String userMessage = ... // Decide what the message you will show to users

        HttpStatus status = HttpStatus... // Decide what the status your response will be have, for example HttpStatus.CONFLICT

        ApiErrorMessage message = new ApiErrorMessage(userMessage, status, reqPath); // Create your custom error message

        return new ResponseEntity<>(message, status); // return response to users
    }

    // other handlers
}

或者您可以像官方 example 中那样更轻松地实现此处理程序.

关于spring-boot - 使用 @RepositoryRestResource 时如何改进错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50273906/

相关文章:

spring-boot - 带有突变 Spring Boot 的 Graphql

java - Spring 将entitymanager getResultList结果转换为JSON

spring-data-jpa - Spring Data Cassandra Reactive - "MappingException Couldn' t 找到类型类 java.lang.Object 的 PersistentEntity”

java - 外键对 POST 的结果不起作用,但 GET 有效

java - JPA 存储库概念是一个通用概念还是由 Spring 框架创造的?

spring - 404关于设置关联资源

java - 如何限制某些用户使用 PUT 和 Spring Data Rest 编辑对象的所有属性?

java - Spring Boot Autowiring 服务 java.lang.NullPointerException

java - 在 POST 请求中反序列化 LocalDateTime 时出错

java - 带有可选@Param 的 Spring 数据查询方法