Last active
May 13, 2020 16:00
-
-
Save bverbeken/8418397 to your computer and use it in GitHub Desktop.
convert spring field errors to json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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