Skip to content

Commit

Permalink
fix JSON errors creation (#97)
Browse files Browse the repository at this point in the history
  • Loading branch information
gibarsin authored Feb 4, 2017
1 parent ecb06e1 commit 3d535bc
Showing 1 changed file with 25 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,32 +21,43 @@ public Response toResponse(final ConstraintViolationException e) {
LOGGER.warn("Exception: {}", (Object[]) e.getStackTrace());
final StringBuilder responseEntity = new StringBuilder();

responseEntity.append("{ errors: [\n");
for (ConstraintViolation<?> cv : e.getConstraintViolations()) {
final String propertyName;
final Iterator<Path.Node> iterator = cv.getPropertyPath().iterator();
Path.Node next = null;

while(iterator.hasNext()) {
next = iterator.next();
}

propertyName = next.getName();
responseEntity.append("{ \"errors\": [\n");
final Iterator<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations().iterator();
// for (ConstraintViolation<?> cv : e.getConstraintViolations()) {
while(constraintViolations.hasNext()) {
final ConstraintViolation<?> cv = constraintViolations.next();

responseEntity.append("{");
responseEntity
.append("\"")
.append(propertyName)
.append(getPropertyName(cv))
.append("\"")
.append(":")
.append("\"")
.append(cv.getMessage())
.append("\"")
.append("},")
.append("\n");
.append("}");

if(constraintViolations.hasNext()) {
responseEntity.append(", ");
}

responseEntity.append("\n");
}
responseEntity.append("] }");
return Response.status(Response.Status.BAD_REQUEST).entity(responseEntity.toString()).build();
}

private String getPropertyName(final ConstraintViolation<?> cv) {
final Iterator<Path.Node> iterator = cv.getPropertyPath().iterator();

Path.Node next = null;

while(iterator.hasNext()) {
next = iterator.next();
}

return next.getName();
}

}

0 comments on commit 3d535bc

Please sign in to comment.