我在 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对于此类异常,从根本原因中提取约束名称,进行分析并为用户创建相应的消息。
已更新
您应该检查应用程序日志以确定必须处理哪个异常。如果我没有误认为违反约束,我们必须处理 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/