使用@RepositoryRestResource 时如何改进错误响应 [英] How to improve error responses when using @RepositoryRestResource
问题描述
我在 PagingAndSortingRepository
上使用 spring 的 @RepositoryRestResource
注释.
I'm using spring's @RepositoryRestResource
annotation on a PagingAndSortingRepository
.
当我向相应的端点发送错误的负载时,发回的错误响应很难解析,例如
When I send an erroneous payload to the corresponding endpoint, the error responses that are sent back are hard to parse, e.g.
{
"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"
}
有没有办法配置消息,所以很清楚哪个字段(这里:电子邮件)导致了错误?
Is there any way to configure the messages, so it is clear which field (here: email) caused the error?
推荐答案
关于错误处理 - 你可以实现一个 自定义异常处理程序针对此类异常,从根本原因中提取约束名称,对其进行分析并为用户创建相应的消息.
Regarding the error handling - you can implement a custom exception handler for such exceptions, extract the constraint name from the root cause, analyze it and create a corresponding message for the user.
Some error handling examples: 1, 2.
更新
您应该检查应用日志以确定您必须处理的异常.如果我没有误认为违反约束,我们必须处理org.springframework.dao.DataIntegrityViolationException
,例如:
You should check the app log to determine which exception you have to handle. If I'm not mistaken for constraint violation we must handle org.springframework.dao.DataIntegrityViolationException
, for example:
@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
}
或者你可以更容易地实现这个处理程序,就像官方的 示例.
Or you can implement this handler easier as in the official example.
这篇关于使用@RepositoryRestResource 时如何改进错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!