Reputation: 96
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)=([email protected]) 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?
Upvotes: 2
Views: 715
Reputation: 30349
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.
UPDATED
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.
Upvotes: 3