使用@RepositoryRestResource时如何改善错误响应

时间:2018-05-10 13:20:09

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

我在@RepositoryRestResource上使用了弹簧PagingAndSortingRepository注释。

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

{
  "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"
}

有没有办法配置邮件,所以很清楚哪个字段(这里:电子邮件)导致错误?

1 个答案:

答案 0 :(得分:2)

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

一些错误处理示例:12

<强>已更新

您应该检查应用程序日志以确定您必须处理的异常。如果我没有误认为违反约束,我们必须处理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中一样轻松实现此处理程序。