Skip to content

Instantly share code, notes, and snippets.

@bverbeken
Last active May 13, 2020 16:00
Show Gist options
  • Save bverbeken/8418397 to your computer and use it in GitHub Desktop.
Save bverbeken/8418397 to your computer and use it in GitHub Desktop.
convert spring field errors to json
@RequestMapping(method = POST)
@ResponseBody
public ResponseEntity<?> submit(@Valid MyRequestType request, BindingResult result) {
if (result.hasErrors()) {
return new ResponseEntity<>(getErrorsInASaneFormat(result), BAD_REQUEST);
}
// do stuff
return new ResponseEntity(CREATED);
}
private Map<String, String> getErrorsInASaneFormat(final BindingResult result) {
return new HashMap<String, String>() {{
for (FieldError error : result.getFieldErrors()) {
put(error.getField(), error.getDefaultMessage());
}
}};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment